R ggplot将xtick从完整日期更改为星期几

问题描述 投票:3回答:2

我想将我的线条图上的xtick从日期更改为文本(显示星期几的名称。

我有以下代码,但xtick目前没有显示。谁能帮我?

lab_day <- c('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 
'Saturday', 'Sunday')
ggplot(stats.gender.wdayF, aes(x=date)) +
  geom_line(aes(y=stats.gender.wdayF$sum), color = 'red') + 
  geom_point(aes(y=stats.gender.wdayF$sum), color = 'red') +
  geom_line(aes(y=stats.agg.wday$sum), color = 'grey') + 
  geom_point(aes(y=stats.agg.wday$sum), color = 'grey') +
  scale_x_date(labels = lab_day) +
  xlab("") +
  ylab("Number of runs") 

dataset looks like:
date, sum
17/12/2017, 1
18/12/2017, 10
19/12/2017, 25
20/12/2017, 2
21/12/2017, 33
22/12/2017, 5
22/12/2017, 11
r ggplot2
2个回答
1
投票

我建议你在另一列中创建日期的名称,然后使用scale_x_discrete()来制作x_axis标签。这会容易得多。

例如:

library(dplyr)
library(data.table)

stats.gender.wdayF <- read.table(text = "date2 sum gender
17/12/2017 1 m
18/12/2017 10 F
19/12/2017 25 m 
20/12/2017 2 m
21/12/2017 33 m
22/12/2017 5 m
22/12/2017 11 F", header = T)%>% as.data.table()

stats.gender.wdayF[, lab_day2 := weekdays(date2 %>% as.Date())]

ggplot(stats.gender.wdayF, aes(x=date2 %>% as.character())) +
  geom_line(aes(y=sum), color = 'red') + 
  geom_point(aes(y=sum), color = 'red') +
  # geom_line(aes(y=stats.agg.wday$sum), color = 'grey') + 
  # geom_point(aes(y=stats.agg.wday$sum), color = 'grey') +
  # scale_x_date(date_labels = '%d %b %Y', date_minor_breaks = '1 day') +
  scale_x_discrete( labels  = stats.gender.wdayF$lab_day2 %>% paste(stats.gender.wdayF$date2, sep = '\n'))  
  # xlab("") +
  # ylab("Number of runs") 

enter image description here


0
投票

尝试将format =“%A”添加到scale_x_date()函数中 - 我相信应该修复它...

如果这不起作用,根据tidyverse,“给出标签的字符向量(必须与breaks长度相同)”。在你的情况下breaks是null所以我觉得这可能是问题。也许尝试添加break参数?

© www.soinside.com 2019 - 2024. All rights reserved.