在r中的条形图x轴上将天数转换为星期几和星期几的名称 [英] Convert day number to day and week name in bar plot x-axis in r

查看:118
本文介绍了在r中的条形图x轴上将天数转换为星期几和星期几的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下数据框,该数据框显示了5周内发生的不同类型的活动,

Considering a data frame as below that shows different types of activities happened within 5 weeks,

      id  Type     Day_index(no)
 1   711  C        16
 2   346  A        30 
 3   569  B        8  
 4    11  A        22 
 5   263  A        29 
 6   510  C        19 
 7   686  B        9  
 8   467  A        11 
 9   478  C        16 
10   202  A        22
11   701  C        22 
12   448  A        5  
13   106  A        19 
14   674  B        8  
15   139 A         25 

如何在r中绘制百分比堆积条形图,x轴显示星期和日期名称,而不是数据框中的日期,如下所示:

How to plot a percentage Stacked Bar Plot in r which x-axis shows weeks and day names instead of the day number in the data frame as below:

推荐答案

也许这更接近您的需求:

Maybe this is closer to what you need :

library(dplyr)
library(ggplot2)

#Days of the week
days <- c("Monday","Tuesday","Wednesday","Thursday","Friday", "Saturday","Sunday")

df %>% 
 mutate(week = paste('Week', ceiling(Day_index/7)), 
        day = factor(days[Day_index %% 7], levels = days)) %>% 
 add_count(week, day) %>% 
 group_by(week) %>%
 mutate(n = round(n/sum(n) * 100, 2)) %>%
 ggplot() + aes(day, n, fill = Type, label = paste(n, "%")) + 
 geom_bar(stat = "identity") + 
 facet_grid(.~week) + 
 scale_x_discrete(drop=FALSE) + 
 geom_text(size = 3, position = position_stack(vjust = 0.5)) + 
 theme(axis.text.x = element_text(angle = 45, hjust = 1))

(包括来自@ dc37的一些建议,以提高可见性.)

(Included some suggestion from @dc37 for better visibility.)

数据

df <- structure(list(id = c(711L, 346L, 569L, 11L, 263L, 510L, 686L, 
467L, 478L, 202L, 701L, 448L, 106L, 674L, 139L), Type = structure(c(3L, 
1L, 2L, 1L, 1L, 3L, 2L, 1L, 3L, 1L, 3L, 1L, 1L, 2L, 1L), .Label = c("A", 
"B", "C"), class = "factor"), Day_index = c(16L, 30L, 8L, 22L, 
29L, 19L, 9L, 11L, 16L, 22L, 22L, 5L, 19L, 8L, 25L)), class = 
"data.frame", row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", 
 "11", "12", "13", "14", "15"))

这篇关于在r中的条形图x轴上将天数转换为星期几和星期几的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆