2

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.

0

1 Answer 1

1

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').

Sign up to request clarification or add additional context in comments.

2 Comments

Now i need to plot three bars and one column. The method described doesn't work for me. I declare first geom_col() and then geom_line() in order to plot the line over the bars. It seems that I can't graph all the bars/columns. It seems strange.
That does sound strange, same method should work just fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.