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

时间:2021-07-20 14:57:16

标签: r ggplot2

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

示例如下:

# 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")) 

正如您从我的数据中看到的,我想创建条形图。使用 clusterNum 列分别显示每个 periodRoad 列总数。因此,我可能有两个基于 Road 列的图表。

我预期的图表可能如下所示 enter image description here

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

也许是这样的:

DECLARE
    v_NAME varchar2(100);    
    v_GENDER nvarchar2(100); 
    v_POSITION nvarchar2(100);   

    CURSOR c1
    IS 
        SELECT * 
        FROM DATA
        ORDER BY id;

BEGIN
    FOR x IN c1 LOOP
        v_NAME := REGEXP_SUBSTR(x.TEXT_NOTE, '[^|]+', 1, 1);
        v_GENDER := REGEXP_SUBSTR(x.TEXT_NOTE, '[^|]+', 1, 2);
        v_POSITION := REGEXP_SUBSTR(x.TEXT_NOTE, '[^|]+', 1, 3);
        DBMS_OUTPUT.PUT_LINE(v_NAME ,v_GENDER ,v_POSITION); --test
    END LOOP;
END;

enter image description here

答案 1 :(得分:1)

或者,如果您正在寻找单独的图表,您可以使用 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)

enter image description here

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()

enter image description here