0

I want to visualize how many copies of each product category are sold (2nd column on table below) and add line that represents % market share (3rd column) Table I used sec_axis function to adjust second axis scale but it seems like data doesnt want to connect with it and it still operate on the first axis scale.

       tabela %>% ggplot() +
      geom_col(aes(x =`Przedział Cenowy`,  y = `Sprzedaz przypadająca na jeden tytuł `), 
fill = "blue", alpha = .4)+
      geom_point(aes(x =`Przedział Cenowy`, y = `Liczba Sprzedanych Kopii / Całkowitą sprzedaż [%]`), color= "red") +
      geom_line(aes(x =`Przedział Cenowy`, y = `Liczba Sprzedanych Kopii / Całkowitą sprzedaż [%]`), color= "red") +
      scale_y_continuous(sec.axis = sec_axis(~./2800, name = "Procent"))

Running code adds the second axis as desired with correct units that should allow to visualize % market share but points and lines look like they still operate on the first axis. Chart result When I change ylim=c(0,150) it looks like that changed ylim

So for me it clearly looks like points and line are still operating on the first not the second axis. How could I fix it?

  • Welcome to StackOverflow. Thanks for asking your question clearly and sharing your code. However, in future please [do not use images of code/data](//meta.stackoverflow.com/q/285551). Instead export data in a copy-pasteable format such as by using `dput(tabela)`. Also see [this](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for tips on sharing good examples in your questions. – Dan Adams Dec 26 '21 at 20:30

1 Answers1

0

You need to scale the data that should appear on the sec_axis by the reciprocal of the scaling factor used to create that axis. So your code should read:


tabela %>% 
   ggplot() +
   geom_col(aes(x =`Przedział Cenowy`,  
                y = `Sprzedaz przypadająca na jeden tytuł `), 
            fill = "blue", 
            alpha = .4)+
   geom_point(aes(x =`Przedział Cenowy`, 
                  y = 2800*(`Liczba Sprzedanych Kopii / Całkowitą sprzedaż [%]`)), 
              color= "red") +
   geom_line(aes(x =`Przedział Cenowy`, 
                  y = 2800*(`Liczba Sprzedanych Kopii / Całkowitą sprzedaż [%]`)), 
              color= "red") +
      scale_y_continuous(sec.axis = sec_axis(~./2800, name = "Procent"))

Dan Adams
  • 4,971
  • 9
  • 28
  • That works. I thought data will automatically read valuse from second axis. Thanks! – Piotr Leja Dec 27 '21 at 10:18
  • If this solves your problem, please [accept the answer](https://stackoverflow.com/help/someone-answers). You need to manually scale both the `sec_axis` and the data that goes with it since `{ggplot2}` only operates on a single scale under the hood. – Dan Adams Dec 27 '21 at 12:26