r-处理ggplot2中不常见的日期结构



我有一个数据集,它包含以下日期变量。

dat$Leads_MONTH
 [1] "10-Jan" "10-Feb" "10-Mar" "10-Apr" "10-May" "10-Jun" "10-Jul" "10-Aug" "10-Sep" "10-Oct" "10-Nov" "10-Dec" "11-Jan" "11-Feb" "11-Mar" "11-Apr"
[17] "11-May" "11-Jun" "11-Jul" "11-Aug" "11-Sep" "11-Oct" "11-Nov" "11-Dec" "12-Jan" "12-Feb" "12-Mar" "12-Apr" "12-May" "12-Jun" "12-Jul" "12-Aug"
[33] "12-Sep" "12-Oct" "12-Nov" "12-Dec" "13-Jan" "13-Feb" "13-Mar" "13-Apr" "13-May" "13-Jun" "13-Jul"

我想使用ggplot2在x轴上绘制这些数据,但此任务存在一些问题。有没有办法让ggplot2将Leads_MONTH格式化为日期格式,然后使用ggplot2进行绘图。

ggplot(dat, aes(Leads_MONTH, LEADSforester)) +
   geom_bar(stat="identity", fill="#336699") + 
     theme(axis.text.x = element_text(angle = 90, hjust = 1))

上面的代码生成了一个绘图,但x轴上的日期不在写入顺序中。

我试图将变量设置为日期,但没有任何运气。

> dat$Leads_MONTH <- as.Date(dat$Leads_MONTH)
Error in charToDate(x) : 
  character string is not in a standard unambiguous format

对于条形图,您可以手动将Leads_MONTH转换为因子并指定级别。

dat <- data.frame(Leads_MONTH = c(
"10-Jan", "10-Feb", "10-Mar", "10-Apr", "10-May", "10-Jun", "10-Jul", "10-Aug", "10-Sep", "10-Oct", "10-Nov", "10-Dec", "11-Jan", "11-Feb", "11-Mar", "11-Apr",
"11-May", "11-Jun", "11-Jul", "11-Aug", "11-Sep", "11-Oct", "11-Nov", "11-Dec", "12-Jan", "12-Feb", "12-Mar", "12-Apr", "12-May", "12-Jun", "12-Jul", "12-Aug",
"12-Sep", "12-Oct", "12-Nov", "12-Dec", "13-Jan", "13-Feb", "13-Mar", "13-Apr", "13-May", "13-Jun", "13-Jul"),
LEADSforester = runif(43))
library(ggplot2)
# Convert Leads_MONTH to factor and specify the levels
dat$Leads_MONTH <- factor(dat$Leads_MONTH, levels = dat$Leads_MONTH)
ggplot(dat, aes(Leads_MONTH, LEADSforester)) +
   geom_bar(stat="identity", fill="#336699") + 
     theme(axis.text.x = element_text(angle = 90, hjust = 1))

如果要转换为Date类,则需要添加day并指定参数格式

as.Date(paste0(dat$Leads_MONTH, '-1'), format = '%y-%b-%d')

尝试:

library(zoo)
as.yearmon(dat$Leads_MONTH, format="%y-%b")

要将它们转换为普通日期对象,请将其包装在as.Date

最新更新