首页 > 解决方案 > r中带有重复x轴的自定义条形图

问题描述

鉴于下面的数据显示了每个工作日的事件记录,

    Type    Day of week
1   Week1   Tuesday
2   Week1   Tuesday
3   Week1   Wednesday
4   Week1   Friday
5   Week2   Thursday
6   Week2   Tuesday
7   Week2   Friday
8   Week2   Tuesday
9   Week2   Monday
10  Both    Thursday
11  Both    Monday
12  Both    Friday
13  Both    Thursday
14  Both    Monday
15  Both    Sunday

我怎样才能有一个重复的 x 轴显示两周的条形图,并根据类型列绘制频率(两者都将在两周内出现)。

在此处输入图像描述

标签: rggplot2

解决方案


library(dplyr)
library(ggplot2)

# make the "both" happen every week
both = dd %>% filter(Type == "Both") %>%
  select(-Type) %>%
  merge(data.frame(Type = c("Week1", "Week2")), by = NULL) 

# put the data together
all = dd %>% filter(Type != "Both") %>%
  bind_rows(both)

# put days in right order
all$Dayofweek = factor(all$Dayofweek, 
  levels = c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"))

# plot
ggplot(all, aes(x = Dayofweek)) +
  geom_bar() +
  facet_wrap(~Type)

在此处输入图像描述

使用这些数据:

dd = read.table(text = "    Type    Dayofweek
1   Week1   Tuesday
2   Week1   Tuesday
3   Week1   Wednesday
4   Week1   Friday
5   Week2   Thursday
6   Week2   Tuesday
7   Week2   Friday
8   Week2   Tuesday
9   Week2   Monday
10  Both    Thursday
11  Both    Monday
12  Both    Friday
13  Both    Thursday
14  Both    Monday
15  Both    Sunday", header = T)

推荐阅读