r - 向多折线图添加图例和数据标签
问题描述
我有一个这样的数据框
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")
我没有得到完美的输出,使用任何建议的方法在图表中添加了图例和数据标签。有人可以帮我吗?
解决方案
您应该首先将数据框转换为“长”格式,然后告诉 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 日创建
推荐阅读
- yaml - 如何仅在活动 LTS 甚至当前版本上运行 GitHub 工作流?
- php - 如果子域托管在不同的服务器上,子域上的 SSL 证书是否需要来自同一颁发者?
- reactjs - React JS“npm start”显示无法编译 web-vitals
- javascript - 如何在一个视频结束时连续播放来自不同网站的嵌入多个视频
- python - PyQt5中的窗口切换和线程
- linux - Ubuntu 16.04:在 dockerfile 中运行“apt-get update”命令时出现错误“无法连接到 archive.ubuntu.com:80 (91.189.88.152)”
- conv-neural-network - 为什么 CNN 架构必须将视频分成更小的视频片段来提取 CNN 特征?
- django - 无法在 Django 测试框架中使用 Locust 作为库
- c# - 最小化的winform应用程序的跨线程异常
- go - 需要约束以具有外键,该外键引用 gorm 中的 has-many 关系中的唯一键