Bubs
Bubs

Reputation: 105

cluster bar plot in R

I am trying to create a clustered bar plot for 3 different types of precipitation data. I've been doing various searches, how this might be done in R with a similar data set. However, I couldn't find any good help. enter image description here

This is the dataset I am currently using. I have tried adding multiple geom_bar() but that didn't work out. See attempt below:

ggplot(ppSAcc,aes(x=date,y=as.numeric(Precipitation)))+geom_bar(stat="identity",aes(color="blue"),show.legend=FALSE,size=1)+
    geom_bar(ppMAcc,stat="identity",aes(x=date,y=as.numeric(Precipitation),color="purple"),show.legend = FALSE,size=1)+
    labs(title="Accumulated Solid Precipitation (Snow)",y="Precipitation (mm)")

In my second attempt, I tried creating a dataframe which includes all three precipitation types.

data<-data.frame(date=ppSAcc$date,snow=ppSAcc$Precipitation,mixed=ppMAcc$Precipitation,rain=ppRAcc$Precipitation)

Which gave me the dataframe shown above. This is where I am stuck. I started coding ggplot ggplot(data,aes(x=date)))+geom_bar(position = "dodge",stat = "identity") but I'm not sure how to write the code such that I will have three columns(snow, mixed, rain) for each year. I'm not sure how to set the aes() part.

Upvotes: 1

Views: 371

Answers (1)

dc37
dc37

Reputation: 16178

You need to reshape your dataframe into a longer format before to plot it in ggplot2. You can use pivot_longer function from tidyr:

library(tidyr)
library(dplyr)
library(ggplot2)
library(lubridate)

df %>% pivot_longer(-date, names_to = "var", values_to = "val") %>%
  ggplot(aes(x = ymd(date), y= val, fill = var))+
  geom_col(position = position_dodge())

Does it answer your question ?

If not, please provide a reproducible example of your dataset by following this guide: How to make a great R reproducible example

Upvotes: 1

Related Questions