Change text / tags ggplot legend

I believe this question is slightly different from the similar questions asked here earlier due to the use of scale_fill_brewer( . I am working on choropleth like this https://gist.github.com/233134

It looks like this:

Chloropleth

and a legend like:

legend

I like it, but I want to change the labels on the legend from the cut labels, i.e. (2, 4] to something friendlier, like from 2% to 4% 'or' 2% - 4% . I saw elsewhere that it is easy to change the labels inside the scale _..., as can be seen here I can’t understand where to put the argument label =. Of course, I could change the code choropleth$rate_d , but that seems inefficient. Where should I put the argument labels=c(A, B, C, D...) ?

Here's a snippet of code of interest (for the full code, use the link above)

 choropleth$rate_d <- cut(choropleth$rate, breaks = c(seq(0, 10, by = 2), 35)) # Once you have the data in the right format, recreating the plot is straight # forward. ggplot(choropleth, aes(long, lat, group = group)) + geom_polygon(aes(fill = rate_d), colour = alpha("white", 1/2), size = 0.2) + geom_polygon(data = state_df, colour = "white", fill = NA) + scale_fill_brewer(pal = "PuRd") 

Thank you in advance for your help.

EDIT: USING the DWin method (should have posted this error as this is what I came across before)

 > ggplot(choropleth, aes(long, lat, group = group)) + + geom_polygon(aes(fill = rate_d), colour = alpha("white", 1/2), size = 0.2) + + geom_polygon(data = state_df, colour = "white", fill = NA) + + scale_fill_brewer(pal = "PuRd", labels = lev4) Error: Labels can only be specified in conjunction with breaks 
+6
source share
1 answer

In addition to adding a modified version of the levels, you also need to set the "breaks" parameter to scale_fill_brewer :

 lev = levels(rate_d) # used (2, 4] as test case lev2 <- gsub("\\,", "% to ", lev) lev3 <- gsub("\\]$", "%", lev2) lev3 [1] "(2% to 4%" lev4 <- gsub("\\(|\\)", "", lev3) lev4 [1] "2% to 4%" ggplot(choropleth, aes(long, lat, group = group)) + geom_polygon(aes(fill = rate_d), colour = alpha("white", 1/2), size = 0.2) + geom_polygon(data = state_df, colour = "white", fill = NA) + scale_fill_brewer(pal = "PuRd", labels = lev4, , breaks=seq(0, 10, by = 2) ) 
+10
source

Source: https://habr.com/ru/post/908675/


All Articles