尽管在 aes() 中使用了颜色,但使用 ggplot2 并未显示图例

问题描述 投票:0回答:1

我在显示情节图例时遇到问题。我检查了其他帖子,其中大多数都提到颜色应该在 ggplot 的 aes() 中定义。

所以我有以下数据集:

  date     `N Rx AFTN` `N Tx AFTN`  SumAFTN `N Rx AMHS` `N Tx AMHS`  SumAMHS   SUM_Tx SUM_Total   SUM_Rx
  <chr>          <int>       <int>    <dbl>       <int>       <int>    <dbl>    <dbl>     <dbl>    <dbl>
1 2018_M12    22844731    36682853 59527584     5932852     5942479 11875331 42625332  71402915 28777583
2 2019_M12    31858229    52049649 83907878    23412883    25242891 48655774 77292540 132563652 55271112
3 2020_M12    12788348    27191283 39979631    14769682    18274489 33044171 45465772  73023802 27558030
4 2021_M12    11718972    36313167 48032139    22200241    24076705 46276946 60389872  94309085 33919213
5 2022_M12    13362373    46255935 59618308    32268850    31050963 63319813 77306898 122938121 45631223
6 2023_M12    14479914    50957248 65437162    35808014    34036231 69844245 84993479 135281407 50287928```

and I'm plotting using : 

```  Ylabel = "Number of Million messages"  
  selDataToPlot = "ALL_messages"  
    
    print(ggplot(all_df))+
      geom_point(aes(x=date,y=SUM_Total/1000000))+
      geom_line(aes(x=date,y=SUM_Total/1000000,color=SUM_Total),color="blue",group=1)+
      geom_line(aes(x=date,y=SUM_Rx/1000000, color=SUM_Rx),color="green",group=1) +
      geom_line(aes(x=date,y=SUM_Tx/1000000,color=SUM_Tx),color="red",group=1)  +   
      labs(title=paste(PlotTitle, "\nfor the period",dateSelStart,"-",dateSelEnd, "\n(", dataType,dataFiles,"Statistics)"), x="Date/Time", y=Ylabel)+
      theme(axis.text=element_text(size=8), 
            axis.title=element_text(size=8),
            plot.title=element_text(size=10),
            axis.text.x=element_text(angle=45))```

The result is [![plot][1]][1]

where no legend is shown.

What am I missing?


  [1]: https://i.sstatic.net/HWilKtOy.png
r ggplot2 legend
1个回答
0
投票

当您直接在

color
函数中使用
geom_line()
参数分配颜色时,ggplot 将这些解释为使用特定颜色的指令,而不是将数据映射到美学,这就是生成图例的原因。为了根据数据生成图例,您需要将
color
参数移至
aes()
函数中。这里我使用
scale_color_manual()

ggplot(all_df) +
  geom_point(aes(x = date, y = SUM_Total / 1000000)) +
  geom_line(aes(x = date, y = SUM_Total / 1000000, color = "Total"), group = 1) +
  geom_line(aes(x = date, y = SUM_Rx / 1000000, color = "Rx"), group = 1) +
  geom_line(aes(x = date, y = SUM_Tx / 1000000, color = "Tx"), group = 1) +
  scale_color_manual(values = c("Total" = "blue", "Rx" = "green", "Tx" = "red"),
                     name = "Message Types", labels = c("Total", "Received", "Transmitted")) +
  labs(title = "Plot Title", x = "Date/Time", y = "Messages (in millions)") +
  theme(axis.text = element_text(size = 8), 
        axis.title = element_text(size = 8),
        plot.title = element_text(size = 10),
        axis.text.x = element_text(angle = 45))

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.