首页 > 解决方案 > 如何创建具有 3 列数据集的折线图?

问题描述

我有一个来自 csv 的三列数据源。我使用 read.csv 将其导入 R。数据集如下所示。

      LRV Variance      Date
   1: 101    4.541  9/1/2020
   2: 101    0.000  9/2/2020
   3: 101    8.992  9/3/2020
   4: 101   23.233  9/4/2020
   5: 101    6.347  9/5/2020
  ---                       
1696: 150    4.516 9/30/2020
1697: 150    0.000 10/1/2020
1698: 150    0.000 10/2/2020

我正在尝试生成一个折线图,其中 x 轴为日期,Y 轴为方差,以及表示每个 LRV 的绘图点/线。

我尝试使用 ggplot 来做到这一点。

ggplot(mydata, aes(Date, Variance, colour = LRV)) + geom_point() + geom_path()

但这最终会在每天而不是每个 LRV 内绘制一条线。 这是输出

标签: rggplot2

解决方案


尝试使用这种方法geom_line()(我使用了您的数据,所以有空日期)。这里的代码使用ggplot2

library(ggplot2)
#Format date
df$Date <- as.Date(df$Date,'%m/%d/%Y')
#Code
ggplot(df, aes(Date,Variance, color=factor(LRV),group=factor(LRV)))+
  geom_line()+
  scale_x_date(date_labels = '%Y-%m_%d')

输出:

在此处输入图像描述

使用的一些数据:

#Data
df <- structure(list(LRV = c(101, 101, 101, 101, 101, 150, 150, 150, 
151, 151, 151), Variance = c(4.541, 0, 8.992, 23.233, 6.347, 
4.516, 0, 0, 6, 9, 15), Date = c("09/01/2020", "09/02/2020", 
"09/03/2020", "09/04/2020", "09/05/2020", "09/30/2020", "10/01/2020", 
"10/02/2020", "09/30/2020", "10/01/2020", "10/02/2020")), row.names = c(NA, 
-11L), class = "data.frame")

推荐阅读