首页 > 解决方案 > R:错误:美学必须是长度 1 或与数据相同:x

问题描述

library(ggplot2)
mydata <- data.frame(variable = c(1, 1, 1, 2, 2, 2),
                     value = c(1, 2, 3, 4, 5, 6))
p <- ggplot(data = mydata, aes(x = 1:3, y = value, group = variable, color = variable)) + geom_line()
> p
Error: Aesthetics must be either length 1 or the same as the data (6): x

运行上面的代码给了我错误:Error: Aesthetics must be either length 1 or the same as the data (6): x. 我认为这与我x = 3aes. 我想要绘制的样子是这样的:

在此处输入图像描述

标签: rggplot2

解决方案


您的图表图像的 x 轴标记为“迭代”,但该信息未包含在“mydata”的示例中。如果没有这些缺失的信息,将很难为您提供帮助。

根据您的评论,您可能对设置x 轴的限制感兴趣。在这种情况下,您可以尝试使用类似的东西。

p2 <- ggplot(data = mydata, aes(x = variable, y = value)) + 
  geom_line() +
  xlim(1,3)
p2

推荐阅读