Search code examples
rggplot2axis-labels

Any automated process for recoloring or adding indicators to axis labels based on categories in ggplot?


I have made some bar plots in ggplots and was hoping to indicate that each bar is part of larger category via the axis label. Like the plot below for example:

enter image description here

I understand that I could use aesthetics to recolor the axis labels manually, or mutate the dataframe to call specific colors. (See this post for an example: ggplot color axis labels based on variable)

But is there no automated process in ggplots to do this and generate a legend, similar to fill/ scale_fill?


Solution

  • We can use the ggside package for this. A simple tutorial can be found here.

    Dummy input from the package gapminder:

    Since I don't have your dataframe, I'll use the gapminder dataset as an example.

    library(gapminder)
    
    test_df <- gapminder %>% 
      group_by(country) %>% 
      slice_head(n = 3) %>% 
      arrange(country) %>% 
      head(n = 10)
    
    # A tibble: 10 × 6
    # Groups:   country [4]
       country     continent  year lifeExp      pop gdpPercap
       <fct>       <fct>     <int>   <dbl>    <int>     <dbl>
     1 Afghanistan Asia       1952    28.8  8425333      779.
     2 Afghanistan Asia       1957    30.3  9240934      821.
     3 Afghanistan Asia       1962    32.0 10267083      853.
     4 Albania     Europe     1952    55.2  1282697     1601.
     5 Albania     Europe     1957    59.3  1476505     1942.
     6 Albania     Europe     1962    64.8  1728137     2313.
     7 Algeria     Africa     1952    43.1  9279525     2449.
     8 Algeria     Africa     1957    45.7 10270856     3014.
     9 Algeria     Africa     1962    48.3 11000948     2551.
    10 Angola      Africa     1952    30.0  4232095     3521.
    

    ggplot

    library(tidyverse)
    library(ggside)
    
    ggplot(test_df, aes(country, lifeExp, fill = as.character(year))) + 
      geom_col() + 
      geom_xsidetile(aes(xfill = continent), position = "fill") + 
      scale_xsidey_continuous(breaks = NULL) +
      ggside(x.pos = "bottom", draw_x_on = "main") + 
      theme_ggside_minimal()
    

    Created on 2023-03-08 with reprex v2.0.2