1
votes

I'm learning to use ggplot to plot my data. I found many examples such as ggplot multiple grouping bar and Grouped bar plot in ggplot. However, I cannot adapt their case with my data at this moment.

This is what the sample looks like:

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

As you can see from my data, I want to create bar charts. Showing the total number of clusterNum columns with each period separately with the Road column. So, I might have two graphs based on the Road column.

My expected graph may look like this enter image description here

Thank you for any helps.

2
What's the y-axis value in your sample dataset? - user438383
@user438383 I want to count the total number of clusterNum columns. So, Y-axis is counting? - Yasumin
ah yes sorry, that makes sense. - user438383

2 Answers

1
votes

Maybe something like this:

library(tidyverse)
data1 <- data %>% 
  group_by(clusterNum, Road, period) %>% 
  count() 

ggplot(data1, aes(x=period, y=n, group=clusterNum)) +
  geom_bar(aes(fill = Road),
           position = "dodge",
           stat = "identity")

enter image description here

1
votes

Or if you're looking for separate graphs, you can use 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

With an additional breakout by 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