绘制ggplot中的平均线

时间:2017-12-28 19:58:36

标签: r ggplot2

在ggplot中绘制平均线。

我有以下数据;

structure(list(Region.in.country = c("Andalucia", "Aragon", "Asturias", 
"Canary Islands", "Cantabria", "Castilla-La Mancha", "Castilla y Leon", 
"Cataluna", "Comunidad Valenciana", "Extremadura", "Galicia", 
"Islas Baleares", "La Rioja", "Madrid", "Murcia", "Navarra", 
"Pais Vasco"), count = c(540L, 117L, 74L, 362L, 36L, 150L, 299L, 
952L, 797L, 72L, 283L, 353L, 39L, 1370L, 302L, 46L, 255L)), .Names = c("Region.in.country", 
"count"), row.names = c(NA, -17L), class = c("tbl_df", "tbl", 
"data.frame"), na.action = structure(18L, .Names = "18", class = "omit"))

我试图在ggplot 2中的条形图上添加平均线。平均线是17个区域中count列的avergae。

sum(region$count) / 17

 ggplot(data = region, aes(x = Region.in.country, y = count)) +
   geom_bar(stat="identity") +
   geom_line(data = region, aes(355.7059)) +
   coord_flip()

以上代码返回错误

编辑:

enter image description here

2 个答案:

答案 0 :(得分:4)

这应该可以胜任。感谢bouncyball建议aes(yintercept = mean(count))而不是yintercept = 355.7059

  ggplot(region, aes(x= reorder(Region.in.country, count), count))+
    geom_bar(stat ="identity")+
    coord_flip()+
    xlab("Region")+
    ylab("Counts")+
    geom_hline(aes(yintercept = mean(count)))  

enter image description here

如果要创建有序条形图(通过数值),请务必事先在列上使用reorder()即使您使用 arrange() sort() 对数据进行排序,也不会进行排序。如果您不在其上使用reorder(),则按字母顺序按相应的id变量Region.in.country对其进行排序(如此后发布的其他答案所示) )。

答案 1 :(得分:0)

使用geom_hline,如下所示:

avg <- mean(region$count)

region %>%
  ggplot(aes(x = Region.in.country, y = count)) +
  geom_bar(stat="identity") +
  geom_hline(aes(yintercept = avg)) +
  coord_flip()

result of the code