0

I want to add a different variable on secondary axis, but it seems it only takes some transformed value of primary axis only using the argument sec.axis = sec_axis(trans = ~.(+/-/*, etc)). Run the code up until the coord_flip(). In that chart, I want mpg on primary and disp on secondary axis. How can I do that?

library(tidyverse)
mtcars %>% 
  rownames_to_column() %>% 
  slice(1:5) %>%
  ggplot(aes(x=rowname)) +
  geom_col(aes(y = mpg, fill = factor(carb)), position = "stack") +
  geom_point(aes(y = disp), color = "Orange", size = 5) +
  coord_flip() +
  scale_y_continuous(sec.axis = sec_axis(~ disp_doesn't_word_here))
Geet
  • 2,515
  • 2
  • 19
  • 42
  • 2
    Possible duplicate of [ggplot with 2 y axes on each side and different scales](https://stackoverflow.com/questions/3099219/ggplot-with-2-y-axes-on-each-side-and-different-scales) – bouncyball Oct 10 '19 at 12:43
  • All examples are using the sec.axis = sec_axis(trans = ~. to create the transformed values of the primary axis variable. I have 2 different variables. If I am misreading it, can you please suggest a solution. – Geet Oct 10 '19 at 12:51

1 Answers1

1

library(tidyverse) How about this? You can adjust values for your need.

mtcars %>% 
  rownames_to_column() %>% 
  slice(1:5) %>%
  ggplot(aes(x=rowname)) +
  geom_col(aes(y = mpg, fill = factor(carb)), position = "stack") +
  geom_point(aes(y = disp/10), color = "Orange", size = 5) +
  coord_flip() +
  scale_y_continuous(sec.axis = sec_axis(~ .*10))

enter image description here

Zhiqiang Wang
  • 6,206
  • 2
  • 13
  • 27