更改文本/标签ggplot图例

Tyl*_*ker 6 r ggplot2 choropleth

我相信这个问题与前面提到的类似问题略有不同,因为使用了scale_fill_brewer(.我正在研究类似于这个的一个等值线程https://gist.github.com/233134

看起来像这样:

Chloropleth

和传说一样:

传说

我喜欢它但想要将传奇上的标签从剪切标签(2,4)更改为更友好的标签,如' 2%到4% '或' 2% - 4% '.我在其他地方看到它;很容易改变,因为看到规模_...内标签在这里,我似乎无法弄清楚在何处放置标签=说法.当然可以重新码的我choropleth$rate_d,但是,这似乎是低效的.我应该在哪里放置争论labels=c(A, B, C, D...)

这是感兴趣的代码片段(完整代码使用上面的链接)

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")
Run Code Online (Sandbox Code Playgroud)

提前感谢您的协助.

编辑:使用DWin的方法(应该发布此错误,因为这是我之前遇到的)

> 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
Run Code Online (Sandbox Code Playgroud)

42-*_*42- 10

除了添加级别的修改版本,您还需要将'breaks'参数设置为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) )
Run Code Online (Sandbox Code Playgroud)