john
john

Reputation: 1036

Plot 2 y axis with different scales

I want ggplot2 graph with 2 y axis with different scales. I tried with sec_axis( ) but finding difficulty to scale it.

My code

library(ggplot2)
ggplot(mydf)  +
  geom_line(aes(x=Month, y=SalesRate),stat="identity", color = "red") +
  geom_bar(aes(x=Month,  y=Sales),stat="identity", fill = "blue") +
  scale_y_continuous("SalesRate",
                     sec.axis = sec_axis(~ ., name="Sales")
  )

Desired Graph graph

Upvotes: 1

Views: 163

Answers (1)

Kra.P
Kra.P

Reputation: 15143

You can try this way

mydf %>%
  mutate(Month = ym(Month)) %>%
  ggplot() +
  
  geom_bar(aes(x=Month,  y=Sales ),stat="identity", fill = "steelblue") +
  geom_line(aes(x=Month, y=SalesRate  * 24796.84),stat="identity", color = "greenyellow", lwd = 2) +
  scale_y_continuous("SalesRate",
                     sec.axis = sec_axis(~ ./24796.84, name="Sales")
  )

enter image description here

If you want percentage,

mydf %>%
  mutate(Month = as.POSIXct(ym(Month))) %>% 
  ggplot() +
  
  geom_bar(aes(x=(Month),  y=Sales ),stat="identity", fill = "steelblue") +
  geom_line(aes(x=(Month), y=SalesRate  * 24796.84),stat="identity", color = "greenyellow", lwd = 2) +
  scale_y_continuous("SalesRate",
                     sec.axis = sec_axis(~ (./24796.84)* 100, name="Sales")
  ) +
  scale_x_datetime(labels = date_format("%Y%m"), breaks = date_breaks("months"))

enter image description here

Upvotes: 1

Related Questions