首页 > 解决方案 > ggplot中没有出现的行

问题描述

我有以下数据框data。我正在尝试使用创建线图ggplot,其中我有 2 条线(在 下的两个日期Date),Key作为我的 x 轴,Value作为我的 Y 轴。

structure(list(Date = c("2020-11-01", "2020-11-28", "2020-11-01", 
"2020-11-28", "2020-11-01", "2020-11-28", "2020-11-01", "2020-11-28", 
"2020-11-01", "2020-11-28", "2020-11-01", "2020-11-28", "2020-11-01", 
"2020-11-28"), Key = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 
4L, 5L, 5L, 6L, 6L, 7L, 7L), .Label = c("3M", "2YR", "5YR", "10YR", 
"20YR", "25YR", "30YR"), class = "factor"), Value = c(3.6, 4.25, 
4.22, 4.37, 7.09, 7.065, 9.315, 8.96, 11.65, 11.05, 11.77, 11.145, 
11.73, 11.075)), row.names = c(NA, -14L), class = "data.frame")

这是我用于情节的代码。但是,它没有按预期出现(曲线没有出现在图上,在下面添加了图像)

ggplot(dat2, aes(x = Key, y = Value, col = Date)) +
  geom_line()

在此处输入图像描述

这就是我希望它看起来的样子

在此处输入图像描述

标签: rggplot2

解决方案


您将需要设置组审美。默认情况下,ggplot2 会将组审美设置为所有离散变量的交互。在您的情况下,这会导致每一行都是它自己的组,这意味着实际上没有画线。设置组美学会产生正确的图形:

ggplot(dat2, aes(x = Key, y = Value, col = Date, group=Date)) +
  geom_line()

推荐阅读