【问题标题】:Adding legends and data labels to the multiple line graph向多折线图添加图例和数据标签
【发布时间】:2020-07-28 07:40:37
【问题描述】:

我有一个这样的数据框

x<-seq(1,4,1) 
y1<-round(31,59,123,189)
y2<-c(30,55,180,200)
df <- data.frame(x,y1,y2)

我想在 grph 中绘制带有图例和数据标签的多线图。目前我正在使用以下代码行

ggplot(df, aes(x)) +                   
  geom_line(aes(y=y1,), colour="red") +  
  geom_line(aes(y=y2), colour="green")+
  xlab("X")+ylab("Y")

我没有得到完美的输出,使用任何建议的方法在图表中添加了图例和数据标签。有人可以帮我吗?

【问题讨论】:

    标签: r ggplot2 linegraph


    【解决方案1】:

    您应该首先将数据框转换为“长”格式,然后告诉 ggplot 哪一列表示分组。

    library(tidyverse)
    x<-seq(1,4,1) 
    y1<-c(31,59,123,189)
    y2<-c(30,55,180,200)
    df <- data.frame(x,y1,y2)
    df
    #>   x  y1  y2
    #> 1 1  31  30
    #> 2 2  59  55
    #> 3 3 123 180
    #> 4 4 189 200
    #>   x  y1  y2
    #> 1 1  31  30
    #> 2 2  59  55
    #> 3 3 123 180
    #> 4 4 189 200
    
    #transform your dataframe
    
    df <- df %>% pivot_longer(-x, names_to = "factor", values_to = "value")
    
    ggplot(df, aes(x =x, y=value, group=factor, label = value)) +
      geom_line(aes(colour=factor)) +
      geom_text(hjust = 0, nudge_x = -0.2, aes(colour = factor)) 
    

    reprex package (v0.3.0) 于 2020 年 7 月 28 日创建

    【讨论】:

    • 感谢您的帮助。你能告诉我如何在图表中添加数据标签吗?
    • 数据标签是什么意思?
    • y1和y2列的数据值
    • 查看编辑。如果这是您要找的,请接受答案。
    猜你喜欢
    • 2018-02-14
    • 2021-12-25
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 2014-07-24
    • 2023-01-19
    相关资源
    最近更新 更多