首页 文章

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

提问于
浏览
-9

在我的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()

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

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

    你可以使用 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

相关问题