geom_bar + position_dodge 问题
Issue with geom_bar + position_dodge
我想用我的条形图绘制误差线和文本。为了制作一个漂亮且可读的图,我希望错误栏位于 geom_text
元素的左侧(对于左侧栏)和右侧(对于右侧栏)。我会使用 position_dodge
来执行此操作,但不知何故,如果条形图未分组,这不会产生任何影响。
这是我的代码:
df1 <- data.frame(e=c(0.02,0.02), na=c("A","B"), value=c(0.25, 0.75))
ggplot(df1, aes(x=factor(na), y=value, fill=factor(na)))+
geom_bar(stat="identity", width=0.2)+
geom_errorbar(aes(ymin = value-e, ymax = value+e), width = 0.01, size=0.5,
alpha=.6)+
geom_text(aes(label=paste0(round(value*100,0),"%"), vjust=-0.5),
size=5)
这会产生相同的情节:
ggplot(df1, aes(x=factor(na), y=value, fill=factor(na)))+
geom_bar(stat="identity", width=0.2)+
geom_errorbar(aes(ymin = value-e, ymax = value+e), width = 0.01, size=0.5,
alpha=.6, position=position_dodge(width=0.2))+
geom_text(aes(label=paste0(round(value*100,0),"%"), vjust=-0.5),
size=5)
如何移动误差线 left/right?
谢谢
您可以使用 x 美学来指定误差线的 x 位置。虽然处理这个问题的惯用语是保持错误栏居中,并移动文本(最好垂直)
ggplot(df1, aes(x=factor(na), y=value, fill=factor(na)))+
geom_bar(stat="identity", width=0.2)+
geom_errorbar(aes(x = as.integer(factor(na)) +c(-0.1,0.1), ymin = value-e, ymax = value+e), width = 0.01, size=0.5,
alpha=.6)+
geom_text(aes(label=paste0(round(value*100,0),"%"), vjust=-0.5),
size=5)
我想用我的条形图绘制误差线和文本。为了制作一个漂亮且可读的图,我希望错误栏位于 geom_text
元素的左侧(对于左侧栏)和右侧(对于右侧栏)。我会使用 position_dodge
来执行此操作,但不知何故,如果条形图未分组,这不会产生任何影响。
这是我的代码:
df1 <- data.frame(e=c(0.02,0.02), na=c("A","B"), value=c(0.25, 0.75))
ggplot(df1, aes(x=factor(na), y=value, fill=factor(na)))+
geom_bar(stat="identity", width=0.2)+
geom_errorbar(aes(ymin = value-e, ymax = value+e), width = 0.01, size=0.5,
alpha=.6)+
geom_text(aes(label=paste0(round(value*100,0),"%"), vjust=-0.5),
size=5)
这会产生相同的情节:
ggplot(df1, aes(x=factor(na), y=value, fill=factor(na)))+
geom_bar(stat="identity", width=0.2)+
geom_errorbar(aes(ymin = value-e, ymax = value+e), width = 0.01, size=0.5,
alpha=.6, position=position_dodge(width=0.2))+
geom_text(aes(label=paste0(round(value*100,0),"%"), vjust=-0.5),
size=5)
如何移动误差线 left/right?
谢谢
您可以使用 x 美学来指定误差线的 x 位置。虽然处理这个问题的惯用语是保持错误栏居中,并移动文本(最好垂直)
ggplot(df1, aes(x=factor(na), y=value, fill=factor(na)))+
geom_bar(stat="identity", width=0.2)+
geom_errorbar(aes(x = as.integer(factor(na)) +c(-0.1,0.1), ymin = value-e, ymax = value+e), width = 0.01, size=0.5,
alpha=.6)+
geom_text(aes(label=paste0(round(value*100,0),"%"), vjust=-0.5),
size=5)