更改文本/标签ggplot图例

时间:2012-02-17 02:41:07

标签: r ggplot2 choropleth

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

的等值线

看起来像这样:

Chloropleth

和图例如:

legend

我喜欢它但想要将剪辑上的标签从剪切标签更改为(2,4)更加友好,如' 2%至4% '或' 2% - 4%'。我在其他地方见过它;很容易改变标尺_...内的标签,如here所示。我似乎无法弄清楚在哪里放置labels =参数。我当然可以重新编码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")

提前感谢您的协助。

编辑:使用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

1 个答案:

答案 0 :(得分: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) )