0

I need to generate a plot with bar graph for two variables.

I can create a column graph for one variable like below

df <- head(mtcars)
df$car <- row.names(df)
ggplot(df) + geom_col(aes(x=car, y=disp))

how to go about getting a chart like below ( created in excel) - essentially I need add bar plot of more than one variable.

enter image description here

3
  • Please see stackoverflow.com/questions/3099219/… Commented Dec 21, 2017 at 14:17
  • @Linus - thanks. I will refer to that part for the secondary axis question. Commented Dec 21, 2017 at 15:09
  • Edited the question to only one part Commented Dec 21, 2017 at 15:09

1 Answer 1

2

With ggplot you need to convert data to long format so that one column defines the color and one column defines the y value:

library(tidyr)
df$car = row.names(df)
df_long = gather(df, key = var, value = value, disp, hp)
ggplot(df_long, aes(x = car, y = value, fill = var)) +
  geom_bar(stat = 'identity', position = 'dodge')

enter image description here

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

4 Comments

how can we bring the legend to the top centered horizontally and set the y-axis label to the variable names !!
I'm sure if you search the [ggplot2] tag for those questions you can find excellent solutions!
just an unrelated comment - I see that you are using = rather than <-. Is this generally accepted practice ?
It's uncommon, but it's just fine. I prefer it so I do it.

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.