简体   繁体   中英

Legend error in ggplot using geom_point() and geom_line() for multiple series

I'm trying to plot points and lines from the following dataset.

dados = structure(list(
Vertices = c(0.5, 1, 1.5, 2, 2.5, 3), 
AAA = c(1.8156, 2.2355, 2.4784, 2.6283, 2.7266, 2.7947), 
BBB = c(1.9603, 2.3802, 2.6231, 2.773, 2.8713, 2.9394), 
CCC = c(2.1559, 2.5758, 2.8188, 2.9686, 3.0669, 3.135)), 
row.names = c(NA, 6L), class = "data.frame")

ggplot(data = dados, aes(x = Vertices)) +

  #lower points
  geom_point(aes(y = AAA, color = "purple")) +
  geom_line(aes(y = AAA, color = "purple", linetype ="longdash")) +

  #intermediate points
  geom_point(aes(y = BBB, color = "blue")) +
  geom_line(aes(y = BBB, color="blue", linetype = "dotted")) + 

  #higher points
  geom_point(aes(y = CCC, color = "green")) +
  geom_line(aes(y = CCC, color="green", linetype = "dashed")) +

  scale_color_manual(values = c("purple", "blue", "green"),
                     labels = c("AAA","BBB","CCC")) +

  ggtitle("Curvas Spread Debentures") +
  xlab("Years") + ylab("% points")

#helps visualize numerically
dados 

In summary: The aesthetics colors are not following the code order

"AAA" are the lowest values and supposed to be purple but are being plotted in green and are assigned as "CCC" in the legend.

"BBB" are the intermediate values and supposed to be blue color but are plotted in purple and are assigned as "AAA" in the legend

"CCC" are the highest values and supposed to be green color but are plotted in blue and are assigned as "BBB" in the legend

I also tried to plot only points or only lines to simplify but the colors and legends are also messed up. It is a really simple code that went totally wrong and I don't see the mistake, any thoughts?

Do you mean to do something like this?

library(ggplot2)

tidyr::pivot_longer(dados, cols = -Vertices) %>%
    ggplot() + aes(Vertices, value, color = name) +
    geom_point() + geom_line(aes(linetype=name)) + 
    ggtitle("Curvas Spread Debentures") +
    xlab("Years") + ylab("% points") +
    scale_color_manual(values = c('purple', 'blue', 'green'))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM