Reputation: 21
I want to chart one variable using bars and another using lines in a single plot. Here's a minimal example:
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)")
Here's the resulting plot: bar and line plot
Notice how the line is aligned with the edge of the bars? How can I get the lines to align with the center of the bars?
Thank you!
Upvotes: 2
Views: 172
Reputation: 118
You can add it manually with position_dodge()
. Also, geom_col
is what you use when you want geom_bar
with 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)")
Upvotes: 2