For demonstration we’ll load the amphibian_div_tbl data from the mgrtibbles package (hyperlink includes install instructions). Additionally, we’ll select the columns “iucn_2cat”, “Order”, and “Family” which we will use for plotting. Then we’ll remove any rows with an NA value using tidyr::drop_na.
#Librarylibrary("mgrtibbles")#Dataamphibian_div_tbl <- mgrtibbles::amphibian_div_tbl |>#Select to retain only the iucn_2cat and Order columns dplyr::select(iucn_2cat,Order,Family) |>#Drop any rows with an NA tidyr::drop_na()amphibian_div_tbl
When creating a bar chart with geom_bar() a categorical variable/column can be mapped to the x aesthetic. The function will then calculate the count numbers.
Create a bar chart of the iucn_2catvariable/column. This is a column of categoricalfactors (<fct>) representing IUCN categories of:
LC: Least Concern
nonLC: non Least Concern including Near Threatened, Vulnerable, and Endangered
If there are a lot of unique values in the categorical variable you can map it to the y aesthetic to create a flipped bar chart. This is especially useful if the values have long names that would struggle to fit as labels side by side on the x-axis.
Create a flipped bar chart of the Familycategorical character variable/column.
It is common to map a second categorical variable/column to the fill aesthetic. By default this will create a stacked bar chart where the fill variable is represented by colours filling the bar chart. This is useful is you are more interested in the differences between the x-axis groupings.
Create a stacked bar chart of “iucn_2cat” counts where the fill of the bar chart is coloured by “Order”.
amphibian_div_tbl |> ggplot2::ggplot(aes(x = iucn_2cat, fill = Order)) + ggplot2::geom_bar()
Side-by-side bar chart
When you are interested in the differences within the x-axis groupings you can created a side-by-side bar chart. This is carried out by using the position= option in ggplot2::geom_bar() and setting it to "dodge".
Create a side-by-side bar chart of “iucn_2cat” counts where the fill of the bar chart is coloured by “Order”.
ALthough absolute count values are useful for bar charts you will sometimes want relative proportions. To convert the values so the total x-axis count per group equals 1 you can set position= to "fill".
Create a relative proportion bar chart of “iucn_2cat” counts where the fill of the bar chart is coloured by “Order”.