Indian
Indian

Reputation: 997

R method to allow for bar plot with secondary axis with non-overlapping bars

I want to have non-overlapping bars in this plot code. How to achieve that?

library(ggplot2)

p <- ggplot(mtcars) +
  geom_bar(aes(x=row.names(mtcars), y=qsec), position = position_dodge(), stat="identity", fill = "red") + 
  geom_bar(aes(x=row.names(mtcars), y=wt), position = position_dodge(), stat="identity") + 
  scale_y_continuous(sec.axis = sec_axis(~ .+ max(mtcars$wt), name = "weight")) + 
  xlab("Name of the car") + 
  theme(axis.text.x = element_text(angle = 90))
p 

Upvotes: 1

Views: 68

Answers (1)

user10917479
user10917479

Reputation:

You first want to stack the data in the columns that you would like to plot side-by-side. You can do this with pivot_longer().

library(tidyr)
library(ggplot2)

plot_data <- pivot_longer(cbind(model = factor(rownames(mtcars)), mtcars), cols = c("qsec", "wt"))

p <- ggplot(plot_data) +
  geom_bar(aes(x=model, y=value, fill = name), position = position_dodge(), stat="identity") + 
  scale_y_continuous(sec.axis = sec_axis(~ .+ max(mtcars$wt), name = "weight")) +
  labs(fill = "Variable",
       x = "Name of the car",
       y = "qsec",
       y2 = "weight") +
  theme(axis.text.x = element_text(angle = 90))

p

Upvotes: 1

Related Questions