3

我有这些数据并尝试使用 ggplot2 和比例来格式化 xaxis,有日期和时间。

dput(head(pp))
structure(list(DateTime = structure(c(1362405600, 1362409200, 
1362412800, 1362416400, 1363006800, 1363010400), class = c("POSIXct", 
"POSIXt"), tzone = ""), Day = structure(c(1L, 1L, 1L, 1L, 1L, 
1L), .Label = c("Fri", "Mon", "Sat", "Sun", "Thu", "Tue", "Wed"
), class = "factor"), Total_Logins = c(818832L, 801771L, 787508L, 
731672L, 748872L, 727140L), Unique_Logins = c(732152L, 713380L, 
701348L, 647321L, 672848L, 649453L), Date = structure(c(15768, 
15768, 15768, 15768, 15775, 15775), class = "Date")), .Names = c("DateTime", 
"Day", "Total_Logins", "Unique_Logins", "Date"), row.names = c(1498L, 
1499L, 1500L, 1501L, 1666L, 1667L), class = "data.frame")

library(ggplot2)
library(scales)

ggplot(subset(pp, Day=="Fri"), aes(DateTime, Total_Logins, group=1)) + 
    geom_line() + 
    geom_smooth(method="loess", se=T, size=1) + 
    scale_x_date(breaks = "1 day", labels=date_format("%b-%d-%Y %H"))

我收到此错误:

错误:无效输入:date_trans 仅适用于 Date 类的对象

我的 DateTime 列已格式化为日期。任何想法,我在这里做错了什么?

在此处输入图像描述

4

1 回答 1

5

由于列DateTime包含日期和时间(POSIXct 类),并且您还希望显示 x 轴标签的小时数,您应该使用scale_x_datetime()而不是scale_x_date().

+scale_x_datetime(breaks = "1 day", labels=date_format("%b-%d-%Y %H"))

要更改显示 x 轴刻度的中断,您可以更改breaks="1 day"为,例如,更改为breaks="6 hours"。另一种可能性是仅在实际值可用时显示中断。如果轴文本项太多,则可以更改文本的方向。

+scale_x_datetime(breaks = unique(pp$DateTime), labels=date_format("%b-%d-%Y %H"))+
        theme(axis.text.x=element_text(angle=90,vjust=0.5))
于 2013-04-16T15:35:41.113 回答