jfca283
jfca283

Reputation: 21

ggplot : Plot two bars and one line?

I need to plot two bars and one line. I have 3 data frames as this:

require(ggplot2)    
df.0 <- data.frame(x = c(1:5), y = rnorm(5))
df.1 <- data.frame(x = c(1:5), y = rnorm(5))
df.2 <- data.frame(x = c(1:5), y = runif(5))

ggplot(df.0, aes(x=x, y=y)) + 
  geom_line(aes(x=x, y=y))+
  geom_bar(data=df.1, aes(x=x, y=y),stat = "identity",position="dodge")+
  geom_bar(data=df.2, aes(x=x, y=y),stat = "identity",position="dodge")

I can't manage to plot the bars and the line in the correct way. It should look as the image below.

Plot i need to make

I'm not familiar with ggplot2. I've read a lot of links, and I can't find a post similar to my question. Thanks for your time and interest.

Upvotes: 2

Views: 343

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145775

Combine the data frames - at least the two for the bar plot. Dodging is done within a single geom_bar layer, not between two separate ones.

df_bar = rbind(df.1, df.2)
df_bar$id = rep(c("df.1", "df.2"), times = c(nrow(df.1), nrow(df.2)))

ggplot(df.0, aes(x = x, y = y)) + 
  geom_line() +
  geom_col(data = df_bar, aes(fill = id), position="dodge")

enter image description here

Other changes: no need to repeat aes(x = x, y = y) in every layer. If it's in the original ggplot() it will be inherited. Also geom_col is a nice way of geom_bar(stat = 'identity').

Upvotes: 1

Related Questions