我想在一个图中使用条形图绘制一个变量,而使用线形图绘制另一个变量。 这是一个最小的示例:
df <- data.frame(
Pct_F = c(40,50,60,70,80,90),
Pct_B = c(50,60,70,80,90,95),
Time = c("Pre","Pre","Pre","Post","Post","Post"),
Variable = c("Var1","Var2","Var3","Var1","Var2","Var3")
)
ggplot(df)+
geom_bar(aes(x = Variable, y = Pct_F, fill = Time), stat="identity", width = 0.5, position = "dodge")+
geom_line(aes(x = Variable, y=Pct_B, group = Time, colour=Time), stat="identity", size=2)+
scale_y_continuous(limits = c(0,100))+
coord_flip()+
labs(title="Test Chart", x= "", y = "Percent", caption = "(Note: Bars refer to Pct_F and lines refer to Pct_B)")
这是结果图: bar and line plot
注意线条与条形边缘的对齐方式吗?如何使线条与条的中心对齐?
谢谢!
答案 0 :(得分:2)
您可以使用position_dodge()
手动添加它。另外,geom_col
是您想将geom_bar
与stat = "identity"
一起使用的方式。
library(ggplot2)
df <- data.frame(
Pct_F = c(40,50,60,70,80,90),
Pct_B = c(50,60,70,80,90,95),
Time = c("Pre","Pre","Pre","Post","Post","Post"),
Variable = c("Var1","Var2","Var3","Var1","Var2","Var3")
)
dodge = position_dodge(0.5)
ggplot(df)+
geom_col(aes(x = Variable, y = Pct_F, fill = Time), width = 0.5, position = "dodge")+
geom_line(aes(x = Variable, y=Pct_B, group = Time, colour=Time), stat="identity", size=2, position = dodge)+
scale_y_continuous(limits = c(0,100))+
coord_flip()+
labs(title="Test Chart", x= "", y = "Percent", caption = "(Note: Bars refer to Pct_F and lines refer to Pct_B)")