问题描述
所以假设我有数据集:
date order_sum
2015-01-01 800
2016-08-19 900
2019-04-16 1200
2020-10-28 850
这是我的月度转换:sales$month <- month(sales$date)
这是我在 x 轴上使用的最小值:min <- ymd("2020-11-01")
这是我指定我的 df 的基本图:baseplot <- ggplot(sales,aes(month,order_sum))
我正在尝试制作该月的日期与 order_sum
总和的基本图表,并在 x 轴上将日期显示为 11-2020
。
scale_x_date(limits = c(min,Now),breaks = "1 month",labels = date_format("%m-%Y")) +
scale_y_continuous(labels = function(x) scales::dollar(x,suffix = 'M'),n.breaks = 3,expand = expansion(mult = c(0,0.05))) +
labs(x = "Date",y = "Order Volume")
我回到文本块的错误是这样的:
as.Date.default(e) 中的错误:不知道如何将 'e' 转换为类“Date”
有人知道为什么吗?提前致谢!
解决方法
我想我发现了错误:
library(scales)
library(lubridate)
sales <- data.frame(date = c("2015-01-01","2016-08-19","2019-04-16","2020-10-28"),order_sum = c(800,900,1200,850))
sales$month <- month(as.Date(sales$date))
sales$date <- as.Date(sales$date)
min <- ymd("2020-11-01")
ggplot(sales,aes(date,order_sum)) +
scale_x_date(limits = c(min,as.Date(now())),breaks = "1 month",labels = date_format("%m-%Y")) +
scale_y_continuous(labels = function(x) scales::dollar(x,suffix = 'M'),n.breaks = 3,expand = expansion(mult = c(0,0.05))) +
labs(x = "Date",y = "Order Volume") +
geom_point()
首先,如果你用month() 转换sales$month,你会得到整数。最好使用日期变量。
然后我尝试绘制但没有可用的图形。为什么?因为您定义的最小日期是“2020-11-01”。您的限制是从 2020-11-01 到现在 2021-02-23。您的样本中没有数据点包含在该区间内。