首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >ggplot2中的日期和时间序列图中的月和日,以及年的分面

ggplot2中的日期和时间序列图中的月和日,以及年的分面
EN

Stack Overflow用户
提问于 2015-05-01 01:50:13
回答 4查看 20.8K关注 0票数 17

当我在ggplot2中多年使用facet时,我希望monthday都在时间序列图的x轴上。我的MWE如下:

代码语言:javascript
运行
复制
set.seed(12345)
Date <- seq(as.Date("2010/1/1"), as.Date("2014/1/1"), "week")
Y <- rnorm(n=length(Date), mean=100, sd=1)
df <- data.frame(Date, Y)

df$Year <- format(df$Date, "%Y")
df$Month <- format(df$Date, "%b")
df$Day <- format(df$Date, "%d")

df$MonthDay <- format(df$Date, "%d-%b")


p <- ggplot(data=df, mapping=aes(x=MonthDay, y=Y, shape=Year, color=Year)) + geom_point() +geom_line(aes(group = 1))
p <- p + facet_grid(facets = Year ~ ., margins = FALSE) + theme_bw()
print(p)

我尝试使用以下命令控制x轴标签

代码语言:javascript
运行
复制
p + scale_y_continuous() + scale_x_date(labels = date_format("%d-%b"))

但它会抛出以下错误消息。

代码语言:javascript
运行
复制
Error: Invalid input: date_trans works with objects of class Date only
EN

Stack Overflow用户

发布于 2015-05-01 02:08:34

看起来就是这样的.我刚刚手动创建了标签..。

代码语言:javascript
运行
复制
library("ggplot2")
library("scales")
set.seed(12345)
Date <- seq(as.Date("2010/1/1"), as.Date("2014/1/1"), "week")
Y <- rnorm(n=length(Date), mean=100, sd=1)
df <- data.frame(Date, Y)

df$Year <- format(df$Date, "%Y")
df$Month <- format(df$Date, "%b")
df$Day <- format(df$Date, "%d")

df$MonthDay <- format(df$Date, "%d-%b")
df$MonthDay2 <- df$MonthDay
# only show every third label... otherwise it's too crowded
df$MonthDay2[as.numeric(row.names(df))%%3!=0] <- ""
labels <- df$MonthDay2

p <- ggplot(data=df, mapping=aes(x=MonthDay, y=Y, shape=Year, color=Year)) + geom_point() +geom_line(aes(group = 1))
p <- p + facet_grid(facets = Year ~ ., margins = FALSE) + theme_bw()
p + scale_y_continuous() + scale_x_discrete(labels=labels) + 
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, size = 8))

票数 3
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29974535

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档