使用此数据帧("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")
发布于 2015-03-13 03:58:04
您只需将group = 1
添加到ggplot或geom_line aes()中。
对于折线图,必须对数据点进行分组,以便它知道要连接哪些点。在这种情况下,很简单--所有的点都应该连接在一起,所以group=1。当使用更多的变量并绘制多条线时,线的分组通常是通过变量来完成的。
参考:Cookbook for R, Chapter: Graphs Bar_and_line_graphs_(ggplot2), Line graphs.
试试这个:
plot5 <- ggplot(df, aes(year, pollution, group = 1)) +
geom_point() +
geom_line() +
labs(x = "Year", y = "Particulate matter emissions (tons)",
title = "Motor vehicle emissions in Baltimore")
发布于 2014-11-23 05:36:10
你得到这个错误是因为你的一个变量实际上是一个因子变量。执行
str(df)
来检查这个。然后执行此双变量更改,以保留年份编号,而不是转换为"1,2,3,4“级别编号:
df$year <- as.numeric(as.character(df$year))
编辑:看起来你的data.frame有一个“数组”类的变量,这可能会导致pb。然后尝试:
df <- data.frame(apply(df, 2, unclass))
然后再策划一次吗?
发布于 2019-03-06 02:36:35
我在数据框架上也遇到了类似的问题:
group time weight.loss
1 Control wl1 4.500000
2 Diet wl1 5.333333
3 DietEx wl1 6.200000
4 Control wl2 3.333333
5 Diet wl2 3.916667
6 DietEx wl2 6.100000
7 Control wl3 2.083333
8 Diet wl3 2.250000
9 DietEx wl3 2.200000
我认为x轴的变量应该是数字的,这样geom_line就知道如何连接点来绘制直线。
在我将第二列更改为数字后:
group time weight.loss
1 Control 1 4.500000
2 Diet 1 5.333333
3 DietEx 1 6.200000
4 Control 2 3.333333
5 Diet 2 3.916667
6 DietEx 2 6.100000
7 Control 3 2.083333
8 Diet 3 2.250000
9 DietEx 3 2.200000
然后它就起作用了。
https://stackoverflow.com/questions/27082601
复制相似问题