[英]ggplot2 - How to center confidence interval bars on bar plot
其他帖子已经问过了这个问题,但是我还没有弄清楚如何正确使用position_dodge
。
如何在图表的每个条形图的中心放置每个CI条形图?
df <- structure(list(Ano = c(2012, 2012, 2012, 2016, 2016, 2016),
Grupo = c("Controle", "Tratado", "Total",
"Controle", "Tratado", "Total"),
Margem_Mediana = c(4.4,3.1, 4.2, 3.8, 2.5, 3.6),
Erro_Padrao = c(0.0236, 0.0460, 0.0214, 0.0257, 0.0478, 0.0231)),
class = c("tbl_df", "tbl", "data.frame"),
row.names = c(NA, -6L), .Names = c("Ano", "Grupo", "Margem_Mediana", "CI"))
ggplot(df, aes(x = Ano, y = Margem_Mediana, fill = Grupo)) +
geom_bar(data = subset(df, Grupo != 'Total'),
position = position_dodge(), stat = 'identity') +
geom_errorbar(data = subset(df, Grupo != 'Total'),
aes(ymin = Margem_Mediana - CI,
ymax = Margem_Mediana + CI),
width = 1.5,
size = 0.5)
一种可能的解决方案:
在geom_errorbar
添加position = position_dodge()
参数,并指定条width
。
ggplot(df, aes(x = Ano, y = Margem_Mediana, fill = Grupo)) +
geom_bar(data = subset(df, Grupo != 'Total'),
width = 1.5,
position = position_dodge(),
stat = 'identity') +
geom_errorbar(data = subset(df, Grupo != 'Total'),
aes(ymin = Margem_Mediana - CI,
ymax = Margem_Mediana + CI),
width = 1.5,
position = position_dodge(),
size = 0.5)
ggplot(subset(df, Grupo != 'Total'),
aes(x = as.factor(Ano), y = Margem_Mediana, fill = Grupo)) +
geom_bar(width = 0.8,
position = position_dodge(),
stat = 'identity') +
geom_errorbar(aes(ymin = Margem_Mediana - CI,
ymax = Margem_Mediana + CI),
width = 0.4,
position = position_dodge(width = 0.8)) +
xlab('Ano')
您还可以使用position_dodge()
和geom_errorbar()
的width
参数控制误差线的位置和宽度。
如果您想将误差线居中,则可能需要在geom_bar()
指定width
,例如width = 0.8
(默认值为0.9),并在geom_errorbar()
内部的position_dodge(width = 0.8)
应用相同的值(使用0.9(如果未在geom_bar
设置width
)。 而width
在geom_errorbar
会告诉ggplot误差条的宽度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.