Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bar plot with multiple X-axis (category and Time) in R

I am trying to create a bar plot with using the following sample data:

test  <- data.frame(person=c("A", "B", "C", "D", "E"), 
                    value1=c(100,150,120,80,150),     
                    value2=c(25,30,45,30,30)) 

library(reshape2) # for melt

melted <- melt(test, "person")

melted$cat <- ''
melted[melted$variable == 'value1',]$cat <- "first"
melted[melted$variable == 'value2',]$cat <- "second"

melted$Date <- seq.Date(as.Date("2021-01-01"), as.Date("2021-05-01"), "month")

And I am using the following code to create bar plot:

ggplot(melted, aes(x = cat, y = value, fill = variable)) + 
  geom_bar(stat = 'identity')

And it gives me the following output
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, I would like to create it month wise so that each month has two bars for value 1 and value 2. But when I do x=Date, it creates a stack plot (understandably),
enter image description here
however, I would like to create two bars for each month.

Any guidance please?

>Solution :

You’re just missing position = "dodge":

library(reshape2)
library(ggplot2)

# Make data
test  <- data.frame(person=c("A", "B", "C", "D", "E"), 
                    value1=c(100,150,120,80,150),     
                    value2=c(25,30,45,30,30)) 

melted <- melt(test, "person")

melted$cat <- ''
melted[melted$variable == 'value1',]$cat <- "first"
melted[melted$variable == 'value2',]$cat <- "second"

melted$Date <- seq.Date(as.Date("2021-01-01"), as.Date("2021-05-01"), "month")

# Plot
ggplot(melted, aes(x = Date, y = value, fill = variable)) + 
  geom_bar(stat = 'identity', position = "dodge")

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading