使用此数据框(“df”):
year pollution
1 1999 346.82000
2 2002 134.30882
3 2005 130.43038
4 2008 88.27546
我尝试创建这样的折线图:
plot5 <- ggplot(df, aes(year, pollution)) +
geom_point() +
geom_line() +
labs(x = "Year", y = "Particulate matter emissions (tons)", title = "Motor vehicle emissions in Baltimore")
我得到的错误是:
geom_path:每组只包含一个观察 . 你需要调整群体美感吗?
即使我想要折线图,图表也会显示为散点图 . 我试图用 geom_line(aes(group = year))
替换 geom_line()
但这不起作用 .
在答案中,我被告知要将年份转换为因子变量 . 我做了,问题仍然存在 . 这是 str(df)
和 dput(df)
的输出:
'data.frame': 4 obs. of 2 variables:
$ year : num 1 2 3 4
$ pollution: num [1:4(1d)] 346.8 134.3 130.4 88.3
..- attr(*, "dimnames")=List of 1
.. ..$ : chr "1999" "2002" "2005" "2008"
structure(list(year = c(1, 2, 3, 4), pollution = structure(c(346.82,
134.308821199349, 130.430379885892, 88.275457392443), .Dim = 4L, .Dimnames = list(
c("1999", "2002", "2005", "2008")))), .Names = c("year",
"pollution"), row.names = c(NA, -4L), class = "data.frame")
4 回答
您只需将
group = 1
添加到ggplot或geom_line aes()中 .参考:Cookbook for R, Chapter: Graphs Bar_and_line_graphs_(ggplot2), Line graphs.
试试这个:
您得到此错误,因为您的一个变量实际上是一个因子变量 . 执行
检查这个 . 然后执行此双变量更改以保留年份数而不是转换为“1,2,3,4”级别数:
编辑:看来你的data.frame有一个类“array”的变量,它可能会导致pb . 然后尝试:
和plto
在新的会话中启动R并将其粘贴到:
我的数据框有类似的问题:
我认为x轴的变量应该是数字,因此geom_line知道如何连接点来绘制线 .
我将第二列更改为数字后:
然后它工作 .