我想在GGPLOT中将我的X轴格式化为数年和数月而不是几天

时间:2017-12-05 07:46:45

标签: r ggplot2 lubridate

在我的ggplot电话中,我正在密谋如下X轴只显示标签上的每个生日日期,如20171130等,我希望我的标签像11月17日,12月17日ETC

# Invoke a ggplot with date vs. sessions data, segmented by device category
  ggplot(data = gaDataExt, mapping = aes(x = date, y = pageviews, group = 1, color = deviceCategory) ) + 
  geom_bar(stat = "identity") +
  theme_bw() + 
  labs(x = "date", y = "Pageviews by Device Category") +
  labs(title = "Andy D) Users by Device Category", x="Date", y="Total Page views") +
  ylim(0,NA) 

Sombody向我们提出了一些似乎与我正在寻找的东西无关的内容

gaDataExt %>% 
  mutate(date = ymd(date),
         month = year(date)) %>% 
  group_by(deviceCategory) %>% 
  summarise_all(funs(mean)) %>% 
  ggplot(aes(month, pageviews)) + geom_point() + 
  facet_grid(deviceCategory~.) +
  theme_bw()

这是我当前的输出,你可以看到所有聚集在Axis日期,我想只显示该轴上的月份和年份

enter image description here

gaDataExt %>% 
  mutate(date = ymd(date),
         month = year(date)) %>% 
  group_by(deviceCategory) %>% 
  summarise_all(funs(mean)) %>% 
  ggplot(aes(month, pageviews)) + geom_point() + 
  facet_grid(deviceCategory~.) +
  theme_bw()

是有人建议的,但似乎没有用

这是我正在绘制的数据框的头部

> head(gaData_User)
        date          userType deviceCategory   country            region        city users
1 30-11-2017       New Visitor        desktop Australia          Victoria   Melbourne     2
2 30-11-2017       New Visitor         mobile Australia   New South Wales      Sydney     1
3 30-11-2017       New Visitor         mobile Australia          Victoria   Melbourne     2
4 30-11-2017 Returning Visitor        desktop Australia          Victoria   Melbourne     1
5 30-11-2017 Returning Visitor        desktop Australia          Victoria Warrnambool     1
6 30-11-2017 Returning Visitor        desktop Australia Western Australia       Perth     1

1 个答案:

答案 0 :(得分:0)

您可以使用scale_x_date,一个简单的例子。

last_month <- Sys.Date() - 0:29
df <- data.frame(
  date = last_month,
  price = runif(30)
 )

ggplot(df, aes(date, price)) +
  geom_line() + 
  scale_x_date(date_labels = "%Y-%m")

enter image description here