首页 > 解决方案 > 向多折线图添加图例和数据标签

问题描述

我有一个这样的数据框

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

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

标签: rggplot2linegraph

解决方案


您应该首先将数据框转换为“长”格式,然后告诉 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 包(v0.3.0)于 2020 年 7 月 28 日创建


推荐阅读