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

标签 r ggplot2

我想将线图上的 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

最佳答案

我建议您在另一列中创建日期名称,然后使用 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

关于R ggplot 将 xtick 从完整日期更改为星期几,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47947322/

相关文章:

r - 完全删除并重新安装 R,包括所有软件包

r - 如何修改R本地环境中预先存在的函数

r - ggplot2 中的颜色错误(grDevices::col2rgb(colour, TRUE) 中的错误:无效的 RGB 规范)

r - 在 ggplot2 中对转换后的数据标记重新缩放的值

r - 检查列是否包含来自另一列的值

r - R中的sqrt(9)和sqrt(x=9)有什么区别?

ggplot2中旋转轴标题和调整缩放比例

r - ggplot : Plotting the bins on x-axis and the average on y-axis

r - 如何在水平条形图中绘制各个组件?

r - ggplot 在 map 上以名称为中心