[英]plotting an average line in ggplot
在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
列的平均值。
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()
上面的代碼返回錯誤
編輯:
這應該做的工作。 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)))
如果要創建有序條形圖(按數值),請始終記住事先在列上使用reorder()
。 它會以其他方式不排序即使您使用 arrange()
或 sort()
繪制之前,對數據進行排序。 如果您不使用reorder()
,它將按照相應的id變量Region.in.country
按字母順序排序(如在此后發布的其他答案所示)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.