将图例项目从数字更改为ggplot中的字符

时间:2019-03-15 12:36:43

标签: r ggplot2

我想将诸如18128740之类的图例项中显示的值四舍五入到1800万

enter image description here

这是我的代码:

p<-print(ggplot(data = Map_plot, aes(x = long, y = lat, group = group)) +
    ggtitle(vars$names[k]) +
    geom_polygon(aes(fill=Map_plot[,vars$variables[k]]), color = 'black', size = 0.5) + 
    scale_fill_distiller(palette = "Spectral",
                         limits = c(min(Map_plot[,vars$variables[k]]),
                                    max(Map_plot[,vars$variables[k]])),
                         breaks = seq(min(Map_plot[,vars$variables[k]]),
                                      max(Map_plot[,vars$variables[k]]),
                                      mean(Map_plot[,vars$variables[k]])/2)) +
      coord_fixed(1) +
      theme(
        legend.key = element_rect(fill = NA, colour = "black"),
        legend.key.width = unit(0.4, "cm"),
        legend.key.height = unit(1.5, "cm"),
        legend.spacing.x = unit(0.5, 'cm'),
        legend.spacing.y = unit(2.0, 'cm'),
        legend.text = element_text(size = 9)) +
      guides(fill=guide_colorbar(title='Legend', barwidth = 1, title.vjust = -15)))

  ggsave(p, file=paste0("plot_state_", vars$variables[k],".jpg"), width = 14, height = 10, units = "cm")

1 个答案:

答案 0 :(得分:2)

您可以使用scales库和函数number_format更改标签。从tidyverse参考中考虑以下调整后的示例:

library(maps)
library(scales)

states <- map_data("state")
arrests <- USArrests
names(arrests) <- tolower(names(arrests))
arrests$region <- tolower(rownames(USArrests))

choro <- merge(states, arrests, sort = FALSE, by = "region")
choro <- choro[order(choro$order), ]
choro$assault <- choro$assault * 1e6

ggplot(choro, aes(long, lat)) +
  geom_polygon(aes(group = group, fill = assault)) + 
    scale_fill_distiller(palette = "Spectral",
     label=number_format(scale=1e-6, suffix = " Million") ) # Changes the scale

enter image description here