r - 在 data.frame 的 ggplot 图例中添加信息

标签 r dataframe ggplot2

我想在图例中添加信息,哪个传感器具有该值。

这是我的代码:

z <- data.frame(
       a=c("sensor 1","sensor 2","sensor 3","sensor 4","sensor 5","sensor 6","sensor 7","sensor 8"), 
       b=c(50, 60, 70, 20,90,110,30,100)
     )

cxc <- ggplot(z, aes(x=a, y=b, fill=factor(b))) + 
         geom_bar(width = 1,stat="identity",colour = "black")  + 
         scale_fill_brewer(palette="Blues",type = "seq")+
         geom_text(aes(y = b/2,label = b),color = "red",size = 5)
cxc + coord_polar() + 
  theme_linedraw() + 
  theme(axis.ticks =element_blank(), axis.text.y =element_blank(), axis.title=element_blank(), axis.text.x=element_text(size = 12,angle = 45)) +
  guides(fill = guide_legend(title = "Value and sensor"))

这是我的结果: enter image description here

我想在图例中这样写:

  • 20(传感器 4)
  • 30(传感器 7)
  • 50(传感器 1)

我想保留这种颜色和图形样式。

最佳答案

使用 scale_fill_brewerlabels 参数,并对标签进行排序,以便它们按正确的顺序排列。

cxc <- ggplot(z, aes(x=a, y=b, fill=factor(b))) + 
  geom_bar(width = 1,stat="identity",colour = "black")  + 
  scale_fill_brewer(palette="Blues",type = "seq", labels = paste0(z$b, " (", z$a, ")")[order(z$b)])+
  geom_text(aes(y = b/2,label = b),color = "red",size = 5)
cxc + coord_polar() + 
  theme_linedraw() + 
  theme(axis.ticks =element_blank(), axis.text.y =element_blank(), axis.title=element_blank(), axis.text.x=element_text(size = 12,angle = 45)) +
  guides(fill = guide_legend(title = "Value and sensor"))

关于r - 在 data.frame 的 ggplot 图例中添加信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38202449/

相关文章:

r - 如何用ggplot绘制一列数据框?

r - 使用 plotly rstudio 从数据框创建漏斗图

r - 如何从 R 中的数据框中访问特定行?

r - 无法使用 sf() 和 rnaturalearth() 在 R 中提取湖泊几何数据

r - 如何编写函数列表

r - 如何在ggplot 2中的填充中按变量排序条形图

r - 等值线世界地图

r - 如何在lapply函数中切片数据

r - 使用 R 中的 DataTables 最后对空值进行排序

python - 在不删除行的情况下过滤 Pandas DataFrame