【发布时间】:2021-08-19 13:48:18
【问题描述】:
当我将光标悬停在列标题上时,我的数据框中有一列显示为“未知”。它显示为如下所示的日期,带有head(dataframe)
示例数据:
date<date> courses<int> tasks<int>
1 2020-01-02 14 199
2 2020-01-03 14 246
3 2020-01-06 14 227
4 2020-01-07 14 83
5 2020-01-08 14 116
6 2020-01-09 14 178
我试过了:
- 导入前在 Excel 中将列格式化为“日期”
- 在加载 CSV 和 XLS 文件时将导入设置更改为“日期”
- 将数据作为“字符”导入,然后更改为数字和日期。这确实提供了正确的格式但相同的“未知”标题。
我能够添加一个星期列,因此数据在某些情况下似乎表现为日期,但在其他情况下则不然。
DFweek <- dataframe %>% mutate(Week = week(date))
head(DFweek)
date<date> courses<int> tasks<int> <week><dbl>
1 2020-01-02 14 199 1
2 2020-01-03 14 246 1
3 2020-01-06 14 227 1
4 2020-01-07 14 83 1
5 2020-01-08 14 116 2
6 2020-01-09 14 178 2
该列始终显示为日期类型
> class(dataframe$date)
[1] "Date"
> str(dataframe$date)
Date[1:290], format: "2020-01-02" "2020-01-03" "2020-01-06" "2020-01-07" "2020-01-08" "2020-01-09" "2020-01-10" "2020-01-13" "2020-01-14"
这段代码成功绘制了一个情节
b <- diff(ylim.prim)/diff(ylim.sec)
a <- ylim.prim[1] - b*ylim.sec[1]
dataframeplot <- ggplot(dataframe, aes(date, courses)) +
geom_line() +
geom_bar(aes(y = a + tasks*b), color = "red", stat='identity') +
scale_y_continuous("Open Courses", sec.axis = sec_axis(~ (. - a)/b, name = "Tasks Completed")) +
scale_x_continuous("Month", breaks = 1:12) +
ggtitle("Title") +
theme(axis.line.y.right = element_line(color = "red"),
axis.ticks.y.right = element_line(color = "red"),
axis.text.y.right = element_text(color = "red"),
axis.title.y.right = element_text(color = "red")
)
dataframeplot
我想使用 scale_x_date,但是下面的代码给了我一个错误
> dataframeplot2<- ggplot(dataframe, aes(date, courses)) +
+ geom_line() +
+ geom_bar(aes(y = a + tasks*b), color = "red", stat='identity') +
+ scale_y_continuous("Open Courses", sec.axis = sec_axis(~ (. - a)/b, name = "Tasks Completed")) +
+ scale_x_date("Month", breaks = 1:12) +
+ ggtitle("Title") +
+ theme(axis.line.y.right = element_line(color = "red"),
+ axis.ticks.y.right = element_line(color = "red"),
+ axis.text.y.right = element_text(color = "red"),
+ axis.title.y.right = element_text(color = "red")
+
+ )
> dataframeplot2
Error: Invalid input: date_trans works with objects of class Date only
这是否意味着我的日期列实际上不是日期格式?
【问题讨论】:
-
我认为问题不在于您的数据。问题是您没有将
Date变量传递给breaks。