Geet
Geet

Reputation: 2575

Different variable, not the transformed value of primary axis variable, on secondary axis in ggplot

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))

Upvotes: 1

Views: 244

Answers (1)

Zhiqiang Wang
Zhiqiang Wang

Reputation: 6769

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

Upvotes: 1

Related Questions