79409550

Date: 2025-02-03 17:25:20
Score: 1
Natty:
Report link

You mean like this?

out

library(ggplot2)
    
df <- data.frame(
  category = c('a', 'b', 'c', 'd', 'e'),
  value1 = c(1.02, -0.34, 2.31,  1.15, 0.68),
  value2 = c(-1.14, 2.19, 0.56,  3.12, 1.17),
  value3 = c(0,     0.19, 3.18, -1.14, 2.12)
)

scale_factor <- diff(range(df$value2)) / diff(range(df$value3))

ggplot(df, aes(x = value1)) +
  geom_line(aes(y = value2, color = "Value 2")) +
  geom_line(aes(y = value3 * scale_factor, color = "Value 3")) +
  scale_y_continuous(
    name = "Value 2",
    sec.axis = sec_axis(~./scale_factor, name = "Value 3")
  ) +
  scale_color_manual(values = c("Value 2" = "blue", "Value 3" = "red")) +
  labs(x = "Value 1", color = "Variables") +
  theme_minimal()
Reasons:
  • Probably link only (1):
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • High reputation (-1):
Posted by: dog