[英]How to plot total cumulative row count over time ggplot
我想要做的只是隨着時間的推移繪制一個累積的行數(這樣到 2021 年,圖表線已經達到 73 條)。 我對 r 很陌生,我覺得這真的很容易,所以我不知道為什么它不起作用。
我的數據如下所示:
ID name year
73 name73 2021
72 name72 2021
71 name71 2019
70 name70 2017
69 name69 2015
68 name68 2015
我試過這段代碼,它有點工作,但有時這條線似乎不對,因為我只想要一個累積計數。
ggplot(df, aes(x=year, y=ID)) +
geom_line()
任何幫助將非常感激!
在繪圖之前按年份和 ID 對數據進行排序,它將從第一年到最后一年,並且在一年內,較小的 ID 在前。
x <- 'ID name year
73 name73 2021
72 name72 2021
71 name71 2019
70 name70 2017
69 name69 2015
68 name68 2015'
df <- read.table(textConnection(x), header = TRUE)
library(ggplot2)
i <- order(df$year, df$ID)
ggplot(df[i,], aes(x=year, y=ID)) +
geom_line()
由reprex 包(v2.0.1)於 2022-07-08 創建
我不知道問題要求的另一種方法是按年份匯總 ID,保持每年的最大值。
下面的代碼執行此操作並直接通過管道傳輸到繪圖,而無需在全局環境中創建額外的數據集。
aggregate(ID ~ year, df, max) |>
ggplot(aes(x=year, y=ID)) +
geom_line()
由reprex 包(v2.0.1)於 2022-07-08 創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.