0

如何以“2013-07-01 00:30:00”的形式更改 x 轴的标签?

library(ggplot2)

a<-as.POSIXlt("2013-07-01 00:30:00")
b<-as.POSIXlt("2013-07-5 00:30:00")
aI<-as.numeric(a)
bI<-as.numeric(b)

times<-sample(seq(aI,bI,by=2),100)
ggplot(, aes(x=times)) + 
geom_histogram(aes(y=..count..),binwidth=10000, colour="black") +
theme(axis.text.x = element_text(angle=45))

我正在寻找一个添加曲线的函数

 geom_density(alpha=.2, fill="#FF6666")

但在上图中,曲线适合 ..count.. 属性。

4

1 回答 1

1

您将数字 x 值传递给ggplot. 您应该传递日期时间值并使用scale_x_datetime

times <- sample(seq(a, b, by = 2), 100)

library(scales)
ggplot(, aes(x = times)) + 
  geom_histogram(aes(y= ..count.. ), binwidth = 10000, colour = "black") +
  theme(axis.text.x = element_text(angle = 45)) +
  scale_x_datetime(labels = date_format("%Y-%m-%d %H:%M:%S"))

您无法将密度添加到绘图中,因为 y 轴刻度不适合(无论是密度还是​​来自 的计数stat_density)。如果您只关心密度曲线的形状,您可以使用geom_density(alpha = .2, fill = "#FF6666", aes(y = ..scaled.. * 7.5)).

编辑:

根据您的评论,您似乎想要这个:

ggplot(, aes(x = times)) + 
  geom_histogram(aes(y= ..density..), binwidth = 10000, colour = "black") +
  theme(axis.text.x = element_text(angle = 45)) +
  scale_x_datetime(labels = date_format("%Y-%m-%d %H:%M:%S")) +
  geom_density(alpha = .2, fill = "#FF6666")

这很令人困惑,因为您y = ..count..在其中明确指定geom_histogram(尽管它是默认设置)。

于 2013-08-14T09:19:54.890 回答