r - 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
有人可以告诉我我做错了什么吗?谢谢
解决方案
请注意,在使用时,melt
您将数字和字符值组合在一起,这使value
列成为字符,因此您看到的数字实际上是字符而不是数字。
要解决手头的问题,您需要将Col_A
column 转换为 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))
推荐阅读
- swift - UIToolBar 设置 isEnabled 从其他 viewControllers
- c++ - getline 设置故障位以及 eof
- r - 如何使用 R 清洁城市和州(全称和缩写)
- reactjs - 如何整合外部反应
- java - java容器对象交换数组方法
- javascript - 我的两个 Jquery 脚本相互干扰
- python - Tensorflow seq2seq 聊天机器人总是给出相同的输出
- bash - 如何检查是否在 bash 中传入了空的命名参数?
- node.js - 完成从 express 中删除 api 后如何发出另一个 post 请求?
- gdb - 有和没有 GDB 的环境布局差异