【问题标题】:Labeling in ggplotggplot中的标签
【发布时间】:2017-07-10 22:50:13
【问题描述】:

我希望能够在 ggplot 中用每条线的图例标记三个折线图,以便在图表上我们可以知道哪条线与什么相关联。这是我目前的设置:

ggplot(Months, aes(x = Month_Num)) +
  geom_line(aes(y = A), colour = "blue") +
  geom_line(aes(y = B), colour = "green") +
  geom_line(aes(y = C), colour = "red")+
  ylab(label = "Total") +
  xlab("Month Num") +
  ggtitle("Total by Month Num")

如何为 A、B 和 C 线创建图例?谢谢,

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我想这就是你想要的:

    df <- data.frame(month = 1:5, 
                     A = 1:5, 
                     B = 6:10, 
                     C = 11:15)
    
    ggplot(df, aes(x = month)) + 
      geom_line(aes(y = A, col = "A")) + 
      geom_line(aes(y = B, col = "B")) + 
      geom_line(aes(y = C, col = "C")) +
      ylab(label= "Total")
    

    【讨论】:

    • 你应该可以。只需将一个数字作为字符传递给 geom_line() 层中的颜色美学。
    【解决方案2】:

    您可以通过将数据从宽转换为长来以更短的方式完成此操作

    library(tidyverse)
    df %>% gather("var", "total", 2:4) %>% 
      ggplot(., aes(month, total, group = var, colour = var))+
      geom_line()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-28
      • 1970-01-01
      • 1970-01-01
      • 2013-06-24
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多