Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change text/labels ggplot legend

I believe this question is slightly different than similar ones asked on here before because of the use of scale_fill_brewer(. I'm working on a choropleth similar to this one https://gist.github.com/233134

That looks like this:

Chloropleth

and the legend like:

legend

I like it but want to change the labels on the legend from cut looking labels ie (2, 4] to something more friendly like '2% to 4%' or '2% - 4%'. I've seen elsewhere it;s easy to change the labels inside of scale_... as seen here. I can't seem to figure out where to put the labels= argument. I of course could re code choropleth$rate_d but that seems to be inefficient. Where should I put the argument labels=c(A, B, C, D...)?

Here's the piece of the 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 assistance.

EDIT: USing DWin's method (should have posted this error as this is what I ran up against 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
like image 558
Tyler Rinker Avatar asked Feb 17 '12 02:02

Tyler Rinker


1 Answers

Besides 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) )
like image 74
IRTFM Avatar answered Nov 16 '22 09:11

IRTFM