使用此數據框(“df”):year pollution1 1999 346.820002 2002 134.308823 2005 130.430384 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()有geom_line(aes(group = year)),但沒有奏效。在答案中,我被告知要將年份轉換為因子變量。我做了,問題仍然存在。這是輸出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")
3 回答

犯罪嫌疑人X
TA貢獻2080條經驗 獲得超4個贊
您只需要添加group = 1到ggplot或geom_line aes()中。
對于折線圖,必須對數據點進行分組,以便知道要連接的點。在這種情況下,它很簡單 - 所有點都應該連接,所以group = 1。當使用更多變量并繪制多行時,行的分組通常由變量完成。
嘗試這個:
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")

繁花不似錦
TA貢獻1851條經驗 獲得超4個贊
您得到此錯誤,因為您的一個變量實際上是一個因子變量。執行
str(df)
檢查這個。然后執行此雙變量更改以保留年份數而不是轉換為“1,2,3,4”級別數:
df$year <- as.numeric(as.character(df$year))
編輯:看來你的data.frame有一個類“array”的變量,它可能會導致pb。然后嘗試:
df <- data.frame(apply(df, 2, unclass))
并再次策劃?
- 3 回答
- 0 關注
- 1082 瀏覽
添加回答
舉報
0/150
提交
取消