-1

I'm wondering how to best display revenue vs. profit over time in ggplot2. In Excel, I would simply do a secondary y-axis and all is fine. However, ggplot2 isn't really flexible in that regard and using the factor for the secondary axis (in sec.axis) doesn't work.

Do you have any idea how to best plot this, so that the connection (or disconnect) between revenue and price is obvious?

Data would look like this:

revenue <- c(23700, 24400, 24000, 23300, 23800, 23600, 23100, 21800, 21600, 20700, 20100)
profit <- c(1426, 1447, 1245, 1599,  896,  813,  706,  510,  649,  789,  947)
quarter <- c("2020_Q1", "2020_Q2", "2020_Q3", "2020_Q4", "2021_Q1", "2021_Q2", "2021_Q3", "2021_Q4", "2022_Q1", "2022_Q2", "2022_Q3")

Any creative ideas on how to solve this?

Florian
  • 5
  • 6
  • Find a good point to start in this question https://stackoverflow.com/q/3099219/1315767 – Jilber Urbina Nov 29 '22 at 15:36
  • Unfortunately it doesn't. As I said in my question, the factor for the secondary axis doesn't cover the range of the secondary axis. Theoretically, secondary could be negative while primary can only be positive. Therefore it can't be displayed by sec.axis :-( – Florian Nov 29 '22 at 15:40

1 Answers1

0

You could do

library(ggplot2)

ggplot(data.frame(revenue, profit, quarter), aes(quarter, profit)) +
  geom_line(aes(color = 'profit', group = 1), linewidth = 1) +
  geom_line(aes(y = revenue/20, color = 'revenue', group = 1), linewidth = 1) +
  scale_y_continuous(sec.axis = sec_axis(~.x*20, name = 'revenue',
                                         labels = scales::dollar),
                     labels = scales::dollar) +
  labs(colour = NULL, title = 'Profit versus revenue, 2020 - 2023') +
  scale_color_brewer(palette = 'Set1') +
  theme_minimal(base_size = 16) +
  theme(legend.position = 'bottom')

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87