-1

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.

Sue
  • 57
  • 1
  • 7
  • don’t use coord_flip - change x and y in the aes, then you can create a y axis in the usual way, see for example this thread https://stackoverflow.com/questions/3099219/ggplot-with-2-y-axes-on-each-side-and-different-scales – tjebo Nov 24 '21 at 07:57
  • the downvote is mine - your question is one of the most commonly asked here in this forum and it is not clear as to why none of those threads didn’t help you. – tjebo Nov 24 '21 at 07:59

2 Answers2

2

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

Park
  • 14,771
  • 6
  • 10
  • 29
1

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

norie
  • 9,609
  • 2
  • 11
  • 18