我的数据帧中有一列显示为";未知";当我将光标悬停在列标题上时。它显示为以下打印的日期,带有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
这是否意味着我的日期栏实际上不是日期格式?
您应该将scale_x_date("Month", breaks = 1:12)
更改为scale_x_date(breaks = "1 month")
。参见scale_x_date()
的文档:https://www.rdocumentation.org/packages/ggplot2/versions/1.0.1/topics/scale_x_date