Visualizing Modal Split Values: Creating Grouped Bar Charts with ggplot2 and tidyr

Introduction to Grouped Bar Charts for Modal Split Values

In this article, we will explore how to create a grouped bar chart using modal split values from a data frame. The goal is to visualize the percentage of vehicle usage for different path lengths (under 5 km, 5-10km, 10-20km, etc.) in a single plot.

Background

The modal split is a concept used in transportation studies to represent the proportion of trips made using different modes of transport. In this case, we are dealing with car and bike usage for various path lengths. The modal split values can be represented as a percentage, where each mode of transport (car, bike, etc.) has its own column in the data frame.

Reshaping the Data

The main problem with the original code is that the data is in the wide format instead of the long format. To create a grouped bar chart, we need to reshape the data using tidyr::pivot_longer() function.

Step 1: Load Required Libraries

Before reshaping the data, we need to load the required libraries:

library(ggplot2)
library(tidyr)

Step 2: Reshape Data

Now, let’s reshape the data using tidyr::pivot_longer() function, excluding column 1 (VM):

df <- tidyr::pivot_longer(ms_gruppen_d, -1, names_to = "Laenge")

In this step, we are creating a new column called Laenge and converting the values in the original data frame to this new column.

Step 3: Make Distances More Pretty

To make the distances more pretty for printing purposes:

df$Laenge <- factor(df$Laenge, levels = colnames(ms_gruppen_d)[-1])
levels(df$Laenge) <- gsub("Laenge ", "", levels(df$Laenge))

This step is used to remove “Laenge” from the end of each level in the Laenge column.

Step 4: Create a Grouped Bar Chart

Now, we can create a grouped bar chart using ggplot() function:

ggplot(df, aes(Laenge, value, fill = VM)) +
  geom_col(position = "dodge")

In this step, we are creating a grouped bar chart where the x-axis represents the path lengths and the y-axis represents the percentage of vehicle usage. The fill aesthetic is used to group the bars by mode of transport (car, bike, etc.).

Alternative: Stacked Bar Chart

Another option for visualizing modal split values is to use a stacked bar chart:

ggplot(df, aes(Laenge, value, fill = VM)) +
  geom_col(position = "stack")

In this step, we are creating a stacked bar chart where the x-axis represents the path lengths and the y-axis represents the percentage of vehicle usage. The fill aesthetic is used to group the bars by mode of transport (car, bike, etc.).

Conclusion

In this article, we have learned how to create a grouped bar chart using modal split values from a data frame. We also explored an alternative option for visualizing modal split values using a stacked bar chart.


Last modified on 2023-09-13