首页 > 解决方案 > R 语言错误:“date_trans 仅适用于 Date 类的对象”(ggplot2)

问题描述

我正在使用 R 编程语言。我使用了“rehsape”库中的 melt() 函数,因此我的数据看起来像这样:

library(dplyr)
library(ggplot2)
library(reshape2)
library(scales)
    

Table_1 <- data.frame(

"Col_A" = c("2002-01", "2002-01", "2002-01", "2002-02", "2002-02", "2002-02", "2002-03", "2002-03", "2002-03"),
"Col_B" = c("AAA", "AAB", "AAC", "AAA", "ABB", "AAC", "AAA", "AAB", "AAC"),
"Col_C" = c(111, 122.5, 9, 727, 66.4, 3, 992, 88, 12)
    
)

Col_A 是格式为:年-月的日期

表中的列采用以下格式:

Table_1$Col_A = as.character(Table_1$Col_A)
Table_1$Col_B = as.factor(Table_1$Col_B)
Table_1$Col_C = as.numeric(Table_1$Col_C)

从这里开始,我使用了 melt() 函数:

melt = melt(Table_1, id = c("Col_A"))

现在,我想以下列形式绘制这些数据:

p = ggplot(melt, aes(x = Col_A, y=value, group = 1)) + geom_line(aes(color=variable)) + facet_grid(variable ~., scales = "free_y")

我的真实数据有点复杂,我正在尝试修改日期(我有很多日期),以便它们不会显得混乱。

我在尝试:

 p = ggplot(melt, aes(x = Col_A, y=value, group = 1)) + geom_line(aes(color=variable)) + facet_grid(variable ~., scales = "free_y") + scale_x_date(date_labels = "m%-%y", date_breaks = '1 month') + theme(axis.text, x = element_text(angle = 45)) 

其次是:

final = p + scale_y_continuous(labels = comma)

但是,我收到了这个错误:Error: Invalid input: date_trans works with objects of class Date only

有人可以告诉我我做错了什么吗?谢谢

标签: rdateggplot2data-visualization

解决方案


请注意,在使用时,melt您将数字和字符值组合在一起,这使value列成为字符,因此您看到的数字实际上是字符而不是数字。

要解决手头的问题,您需要将Col_Acolumn 转换为 date 类以使用scale_x_date.

library(dplyr)
library(ggplot2)

melt %>%
  mutate(Col_A = as.Date(paste0(Col_A, '-01'))) %>%
  ggplot(aes(x = Col_A, y=value, group = 1)) + 
  geom_line(aes(color=variable)) + 
  facet_grid(variable ~., scales = "free_y") + 
  scale_x_date(date_labels = "%m-%y", date_breaks = '1 month') + 
  theme(axis.text = element_text(angle = 45)) 

推荐阅读