1

My problem is simple but I have not been able to find a post that solves it.

Here is my data set DF:

   Year     CO2Seq       CO2Seq2
1  2000     1135704      1107400
2  2003     3407111      3444508
3  2010     1703555      1661100
4  2015     2271407      2296339

I would like to create a barplot where the bars CO2Seq and CO2Seq2 are next to each other for each year.

For the moment, I have only been able to create a simple barplot for CO2Seq with this script

ggplot(DF,aes(x=factor(Year), y=CO2Seq))+geom_bar(stat="identity")

Could you help me?

Thanks a lot

1 Answer 1

1

ggplot has generally been designed for use with long rather than wide data, so the first step is to reshape your data, then plotting is straightforward.

library(ggplot2)
library(tidyr)

df %>%
  pivot_longer(col = -Year) %>%
  ggplot(aes(x = factor(Year), y = value, fill = name)) +
  geom_bar(stat = "identity", position = "dodge")
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, this looks great but I don't understand what you mean by long rather than wide. I should have mentionned that my real dataset has hundreds of rows. Would it still be important to reshape it?
Yes, it will still need to be reshaped. Compare the difference between your example df (which is wide) and df %>% pivot_longer(col = -Year) (which is long).
Aaaah ok now I get what you mean. This operation allows us to only have one numeric column and makes the grouping easier! Thanks a lot H1!

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.