ggplot2 - plotting 3 axes in R - Stack Overflow

admin2025-04-16  1

I have a data frame like this:

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

I want to ask if there is any possible way to plot a graph with value 1 is in the x-axis, and value 2 and 3 are in the y-axis (one on the left and the other on the right). I hope to be able to receive some help with this. Many thanks!

I have a data frame like this:

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

I want to ask if there is any possible way to plot a graph with value 1 is in the x-axis, and value 2 and 3 are in the y-axis (one on the left and the other on the right). I hope to be able to receive some help with this. Many thanks!

Share Improve this question edited Feb 3 at 17:21 Tim G 6,1651 gold badge3 silver badges19 bronze badges asked Feb 3 at 17:04 user21390049user21390049 1736 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

You mean like this?

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

with Labels instead of lines

# Create the plot with labels instead of lines
ggplot(df, aes(x = value1)) +
  geom_text(aes(y = value2, label = category, color = "Value 2"), size = 4) +
  geom_text(aes(y = value3 * scale_factor, label = category, color = "Value 3"), size = 4) +
  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()
转载请注明原文地址:http://www.anycun.com/QandA/1744759423a87216.html