Home > Back-end >  how to create identical dual discrete y axis
how to create identical dual discrete y axis

Time:11-24

I have a sample data frame as below:

Month<-c("Jan","Feb","Mar","Apr")
Value<-c(12,6,13,3)

xy<-data.frame(Month,Value)
ggplot(xy, aes( x=Month,y=Value)) geom_bar(stat="identity",width=0.6) coord_flip()

how do I add a secondary y axis "Month" that is identical to the first one?

Thank you.

CodePudding user response:

Your Month is discrete and because scale_x_discrete do not have secondary axis options, we need to make another dummy variable mm that's continuous then recode that variable.

xy %>%
  arrange(Month) %>%
  mutate(mm = 1:4) %>%
  ggplot(aes(x=mm,y=Value)) geom_bar(stat="identity",width=0.6)  
   scale_x_continuous(breaks = 1:4,
                      labels = c("Apr", "Feb", "Jan", "Mar"),
                      sec.axis = dup_axis())  
  coord_flip()

enter image description here

CodePudding user response:

Slightly different to Park's answer but the same general idea.

library(ggplot2)

Month <- c("Jan", "Feb", "Mar", "Apr")
Value <- c(12, 6, 13, 3)

xy <- data.frame(Month, Value)

ggplot(xy, aes(x = length(Month):1, y = Value))   geom_bar(stat = "identity", width =
                                                             0.6)  
  scale_x_continuous(
    breaks = length(Month):1,
    labels = Month,
    sec.axis = dup_axis(),
    name = "Months"
  )  
  coord_flip()

Identical duplicate y-axes

  • Related