0

I have a dataframe which I would like to create a bargraph with primary and secondary axes.

geom_bar(data=top_ten_S, aes(x=Combination, y=AvgTopline), stat="identity",fill="red") +
  coord_flip() +
  geom_text(
    data=top_ten_S,
    aes(
      x=Combination, y=AvgTopline,
      label=paste0("R",round(AvgTopline,0)),
      hjust=ifelse(AvgTopline < max(top_ten_S$AvgTopline) / 1.5, -0.1, 1.1), # <- Here lies the magic
    ),
  ) 

my df looks like

top_ten_S <- data.frame(Combination = c("a", "b", "c"),
                    Nrcustomers = c(20, 200, 1900),
                    AvgTopline = c(1000,3000,1500))

I am only able to plot one column with the above code - I would like to a secondary axes so that I could plot Combination against NrCustomers and AvgTopline in

  • Not sure if it is related to the thing you are trying to do, but here is a [previous so question regarding two different y-axis with an answer from Hadley Wickham](https://stackoverflow.com/questions/3099219/ggplot-with-2-y-axes-on-each-side-and-different-scales) – dario Feb 10 '20 at 10:22
  • it is but not directly because I have numerical values, on different scales. Thanks for the recommendation. – Siyabonga Mbonambi Feb 10 '20 at 10:30

1 Answers1

1

Method 1

top_ten_S %>% 
  gather(key, value, -Combination) %>% 
  ggplot(aes(x = Combination, y = value, fill = key)) +
  geom_bar(stat = "identity", position = "dodge") +
  labs(fill = "")

Method 2

top_ten_S %>% 
  gather(key, value, -Combination) %>% 
  ggplot(aes(x = Combination, y = value, fill = key)) +
  geom_bar(stat = "identity", position = "dodge", show.legend = FALSE) +
  facet_grid(. ~ key)

Edit: Method 2

top_ten_S %>% 
  gather(key, value, -Combination) %>% 
  ggplot(aes(x = Combination, y = value, fill = key)) +
  geom_bar(stat = "identity", position = "dodge", show.legend = FALSE) +
  facet_grid(. ~ key, space = "free_y", scales = "free_y") +
  theme(axis.text.x = element_text(angle = 60))
penguin
  • 1,267
  • 14
  • 27
  • This helps, however my challenge is that the y axis i.e.(AvgTopline and NrCustomers) are not on the same scale, thus affecting how the graphs looks like. furthermore my Combination values consists of strings made that are atleast 15 characters in length. – Siyabonga Mbonambi Feb 10 '20 at 10:29
  • To handle different scales, set `scales = "free_y"` in `facet_grid`. See `?ggplot2::facet_grid`. To handle large text length, you may print x axis text at an angle. Please see the edit for clarification. – penguin Feb 10 '20 at 10:34