我有一个小数据框,我想建立一个条形图,其中的线条显示了不同组的平均水平。
数据帧:
cpcost = c("Coll.Punishment","Coll.Punishment", "Ind.Punishment",
"Ind.Punishment")
color = c(0,1,0,1)
mysum = c(0.3408240, 0.2935982, 0.3460490, 0.1267057)
genlevel = c(0.3111111,0.3111111, 0.2181818, 0.2181818)
temp = as.data.frame(cbind(cpcost,color,mysum,genlevel))
所以结果如下:
问题是,现在我正在以一种非常丑陋的方式进行(见下文)。 我基本上首先添加水平误差条。但是因为每个条形的误差条之间有一个小空间:
我还绘制一条水平线来填充误差条之间的这个小空间。 (如果我绘制唯一的水平条,它将从条形图的中间开始。)
我相信有更优雅的方式来达到相同的结果。 我该怎么办?
谢谢!
ggplot(temp, aes(group=cpcost),
y = genlevel ) +
geom_bar(stat = "identity",aes(x = factor(color),
y = mysum,
group=cpcost,
fill = factor(color))) +
geom_errorbar(aes(x=factor(color),
y=genlevel,
ymin=genlevel,
ymax=genlevel,
group=cpcost
)) +
geom_line( aes(x=factor(color), y=genlevel,group=cpcost)) +
labs(x = "Round", y = "Share of Emptying") +
scale_fill_discrete(name='Crime',
labels=c("No", "Yes" )) +
ggtitle('Whistleblowing')+
facet_grid(~cpcost)
答案 0 :(得分:1)
这会给你一个稍微不同的结果,但我希望它足以满足你的需要。它比较干净,使用内置的geom_hline
:
library(ggplot2)
df <- data.frame(cpcost = c("Coll.Punishment", "Coll.Punishment", "Ind.Punishment", "Ind.Punishment"),
color = c(0,1,0,1),
mysum = c(0.3408240, 0.2935982, 0.3460490, 0.1267057),
genlevel = c(0.3111111,0.3111111, 0.2181818, 0.2181818))
ggplot(df) +
geom_col(aes(factor(color), mysum, fill = factor(color))) +
geom_hline(aes(yintercept = genlevel)) +
scale_fill_discrete(name='Crime', labels=c("No", "Yes" )) +
facet_wrap( ~ cpcost) +
labs(x = "Round", y = "Share of Emptying") +
ggtitle('Whistleblowing')