[英]ggplot how show data for the last month period
我有這段代碼。 我的目標是上個月的 plot 數據。 我在 web 上scale_x_date(limits = as.Date
是可能的 所以第一步我在指定的時間范圍內嘗試了 plot 數據...例如 2020-05-01","2020-09-09 但是當我插入此代碼時到我的 ggplot 我得到這個錯誤Invalid input: date_trans works with objects of class Date only
知道有什么問題嗎?
Dataframe 示例:從 csv 讀取
"date","diff"
2020-01-22,555
2020-01-23,99
2020-01-24,287
2020-01-25,493
...
代碼:
##before plot I had to convert date from posix time, to show properly date in plot
conf_all_data$date <- as.POSIXct(conf_all_data$date)
##ggplot
ggplot(conf_all_data, aes(x=date, y=diff, text=paste(date, "\n" , "Confirmed:", diff ))) +
geom_bar(stat='identity',fill='blue') +
scale_x_date(limits = as.Date(c("2020-05-01","2020-09-09"))) +
scale_y_continuous(labels = comma),
tooltip = "text"
此處添加了一條評論:如果日期不是看起來的日期,為什么 ggplot 也可以使用 X 日期軸正確繪制此圖表? 你可以在這里查看我的工作站點http://webcovid19.online/ ,所有圖表中的代碼都相同,只是我用scale_x_date
刪除了有問題的部分,我還添加了截圖
謝謝大家,問題確實是錯誤的日期類型,當我在控制台中進行調試時,我意識到在閱讀 csv 到 DF 是因子類型后,我必須使用 As.date() 進行轉換
Anyway my question is if I want show plot of last month period dataframe, eg today we have 2020-12-08, Is there some Date function with arithmetic operations to get minus 30 days ( or another number) from today to deal with months crossing ?
這是我指定工作時間范圍的工作截圖
ggplot(slovakia_conf_inc, aes(x=date, y=confirmed, text=paste( date, "\n", "confirmed:", confirmed ))) +
geom_bar(stat='identity',fill='blue') +
scale_x_date(breaks = "1 month") +
scale_x_date(limits = as.Date(c("2020-08-01","2020-09-09"))) +
scale_y_continuous(labels = comma),
tooltip = "text"
因為您的date
不是Date
類型。
以economics
數據集和您的限制日期為例:
ggplot(data = economics) +
geom_line(aes(x = date, y = unemploy),
color = "#09557f",
alpha = 0.6,
size = 0.6) +
labs(x = "Date",
y = "US Unemployed in Thousands",
title = "Base Plot") +
scale_x_date(limits = as.Date(c("1999-05-01","1999-09-09"))) +
theme_minimal()
您收到的錯誤類似於嘗試 plot geom_line(aes(x = as.character(date), y = unemploy)
。這會引發
使用as.Date
function 修復它。
好的,我剛剛找到了使用 lubridate 的減法日期的解決方案。 例如
library(lubridate)
date <- As.Date("2009-10-01")
ymd(date) - 5
# [1] "2009-09-26"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.