[英]ggplot2 - How to center confidence interval bars on bar plot
this has been asked on other posts, but I have not figured out how to use position_dodge
correctly. 其他帖子已经问过了这个问题,但是我还没有弄清楚如何正确使用position_dodge
。
How can I center each CI bar in each bar on the graph? 如何在图表的每个条形图的中心放置每个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)
One possible solution: 一种可能的解决方案:
Add position = position_dodge()
argument in your geom_errorbar
and specify your bar width
. 在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)
After some searching (eg this post and this page ), the code can be further improved, 经过一番搜索(例如, 本文和本页 ),可以进一步改善代码,
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')
You can also control the position and width of the error bars using the width
argument in position_dodge()
and geom_errorbar()
您还可以使用position_dodge()
和geom_errorbar()
的width
参数控制误差线的位置和宽度。
If you want to center the error bars, you may need to specify the width
in geom_bar()
say width = 0.8
(looks like 0.9 is the default) and apply the same value in position_dodge(width = 0.8)
inside geom_errorbar()
(use 0.9 if you don't set the width
in geom_bar
). 如果您想将误差线居中,则可能需要在geom_bar()
指定width
,例如width = 0.8
(默认值为0.9),并在geom_errorbar()
内部的position_dodge(width = 0.8)
应用相同的值(使用0.9(如果未在geom_bar
设置width
)。 And width
in geom_errorbar
will tell ggplot the width of the error bars. 而width
在geom_errorbar
会告诉ggplot误差条的宽度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.