R中具有多个条形的分组条形图

安民

我正在学习使用 ggplot 来绘制我的数据。我在ggplot 中发现了许多示例,例如ggplot multiple grouping barGrouped bar plot但是,我目前无法根据我的数据调整他们的案例。

这是样本的样子:

# A tibble: 10 x 3
   clusterNum Road       period     
        <dbl> <chr>      <chr>      
 1          2 Hualampong 06.00-06.15
 2          2 Hualampong 06.00-06.15
 3          2 Hualampong 06.16-06.30
 4          2 Hualampong 06.16-06.30
 5          2 Hualampong 06.16-06.30
 6          3 Hualampong 06.16-06.30
 7          2 Hualampong 06.16-06.30
 8          3 Tonglor    17.46-18.00
 9          3 Tonglor    17.46-18.00
10          3 Tonglor    17.46-18.00
data <- structure(list(clusterNum = c(2, 2, 2, 2, 2, 3, 2, 3, 3, 3),Road = c("Hualampong", "Hualampong", "Hualampong", "Hualampong","Hualampong", "Hualampong", "Hualampong", "Tonglor", "Tonglor","Tonglor"), period = c("06.00-06.15", "06.00-06.15", "06.16-06.30","06.16-06.30", "06.16-06.30", "06.16-06.30", "06.16-06.30","17.46-18.00", "17.46-18.00", "17.46-18.00")), row.names = c(NA,-10L), class = c("tbl_df", "tbl", "data.frame")) 

从我的数据中可以看出,我想创建条形图。clusterNumperiod分别显示总Road所以,我可能有两个基于Road列的图表

我预期的图表可能如下所示 在此处输入图片说明

感谢您的任何帮助。

NovaEthos

或者,如果您正在寻找单独的图表,您可以使用facet_wrap

library(tidyverse)
data2 <- data %>% group_by(period, Road) %>% summarise(clusterNum = sum(clusterNum))
ggplot(data2, aes(x = period, y = clusterNum, fill = period)) + 
  geom_bar(position = "dodge", stat = "identity") + 
  facet_wrap(~Road)

在此处输入图片说明

额外突破clusterNum

library(tidyverse)
data3 <- data %>% group_by(period, Road, clusterNum) %>%
                  count() %>% 
                  data.frame()
data3$n <- as.factor(data3$n)
data3$clusterNum <- as.factor(data3$clusterNum)

ggplot(data3, aes(x = period, y = n, fill = clusterNum)) + 
  geom_bar(position = "dodge", stat = "identity") + 
  facet_wrap(~Road) +
  theme_minimal()

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章