Skip to contents

This vignette introduces two functions developed specifically for creating (almost) presentation-ready bar plot charts with all of Gradient’s best practices applied.

Barplot basics and data format

Gradient’s bar plot functions are built on top of ggplot2, and much like it is in ggplot, the first argument is df, a data.frame that contains the data to be plotted.

Three main parameters, besides df are:

  • x - this is the variable that defines clusters of barplots that will be positioned across the x axis.

  • y - basically column sizes. For g6tr_stacked_bar_plot these are meant to sum up to 1 for each of the x cluster, but it is not required.

  • group - groups to split and color by in each x cluster. g6tr_stacked_bar_plot will display these groups, obviously, stacked one on top of another and g6tr_dodged_bar_plot will display them side-by-side.

You can think of these parameters as of x, y and group aesthetics of geom_col. Similar to ggplot’s aesthetics, these names should be provided unquoted.

Let’s start with some basic examples. This is the data we are going to plot:

library("dplyr")
library("titanic")
library("g6tr.survey")
titanic_df <- titanic::titanic_test

titanic_df <-
  titanic_df %>%
  srv_add_prop_test(x = Sex, y = Embarked) %>%
  select(Embarked, percentage, Sex, everything())

titanic_df

[38;5;246m# A tibble: 8 × 9
[39m
  Embarked percentage Sex    sum_n     n prop_pval prop_pval_adj std_error
  
[3m
[38;5;246m<chr>
[39m
[23m         
[3m
[38;5;246m<dbl>
[39m
[23m 
[3m
[38;5;246m<chr>
[39m
[23m  
[3m
[38;5;246m<int>
[39m
[23m 
[3m
[38;5;246m<int>
[39m
[23m     
[3m
[38;5;246m<dbl>
[39m
[23m         
[3m
[38;5;246m<dbl>
[39m
[23m     
[3m
[38;5;246m<dbl>
[39m
[23m

[38;5;250m1
[39m C             0.392 female   102    40    0.674          0.899    0.048
[4m3
[24m

[38;5;250m2
[39m C             0.608 male     102    62    0.674          0.899    0.048
[4m3
[24m

[38;5;250m3
[39m Q             0.522 female    46    24    0.052
[4m7
[24m         0.211    0.073
[4m7
[24m

[38;5;250m4
[39m Q             0.478 male      46    22    0.052
[4m7
[24m         0.211    0.073
[4m7
[24m

[38;5;250m5
[39m S             0.326 female   270    88    0.352          0.703    0.028
[4m5
[24m

[38;5;250m6
[39m S             0.674 male     270   182    0.352          0.703    0.028
[4m5
[24m

[38;5;250m7
[39m Overall       0.364 female   418   152    1              1        0.023
[4m5
[24m

[38;5;250m8
[39m Overall       0.636 male     418   266    1              1        0.023
[4m5
[24m

[38;5;246m# ℹ 1 more variable: conf_int <dbl>
[39m

For now we are only interested in the first three columns. As you see there are two categorical variables: Embarked - will be used as a cluster variable, the other, Sex - will be used as a variable to color by inside each cluster. And then there’s a numeric variable, percentage which will define column sizes. This is the bare minimum, but we’ll talk about other features that can be displayed later.

In most use cases such kind of data will come out as a result of the g6tr.survey::srv_add_prop_test function, but of course it can be constructed e.g. with the help of dplyr verbs.

Let’s now create some bar plots!

Stacked bar plot

titanic_df %>% g6tr_stacked_bar_plot(Embarked, percentage, Sex)

Dodged bar plot

titanic_df %>% g6tr_dodged_bar_plot(Embarked, percentage, Sex)

Notice:

  • Gradient’s color palette was applied

  • text marks with values are nicely positioned and colored

  • proportion values were automatically converted to percents

As for the last point though, it will not be appropriate when you want to display absolute values rather than percents. In such case, use scale = "none".

titanic_df %>% g6tr_dodged_bar_plot(Embarked, n, Sex, scale = "none")

Column Order

Quite often it makes sense to order plot clusters according to some rule to make it easier for the reader to quickly see where’s the highest proportion of something, where’s the second highest etc. Gradient’s bar plot functions allow this by providing the order_by parameter. The way it works is that you provide the name of one of the categories of group variable and bar plot clusters get reordered by values of this category in descending order (by default) or in ascending order (when setting desc = FALSE).

titanic_df %>% g6tr_stacked_bar_plot(
  Embarked, percentage, Sex,
  order_by = "male",
  desc = FALSE
)

Horizontal Bar Plots

It sometimes may be more reasonable to display bars horizontally rather than vertically. In particular we may want it when cluster names contain lengthy descriptions. Converting a bar plot from vertical to horizontal is as easy as setting flipped parameter to TRUE! Just note that even though in this case cluster categories will be displayed across y axis, you don’t need to swap x and y parameters of bar plot functions.

set.seed(42)
dummy_survey <-
  tibble(response_id = 1:100) %>%
  mutate(
    sex = sample(c("Male", "Female"), n(), replace = TRUE),
    Q1 = sample(c("Yes", "No"), n(), replace = TRUE, prob = c(0.7, 0.3)),
    Q2 = sample(c("Yes", "No"), n(), replace = TRUE, prob = c(0.2, 0.8)),
    Q3 = sample(c("Option A", "Option B", "Option C"), n(),
      replace = TRUE,
      prob = c(0.5, 0.45, 0.07)
    )
  )

attr(dummy_survey$Q1, "label") <-
  "Question A, with some lengthy description which we want to display"
attr(dummy_survey$Q2, "label") <-
  "Question B, with a lengthy description too"
attr(dummy_survey$Q3, "label") <-
  "Question C, select something"

dummy_survey_yn <-
  dummy_survey %>%
  select(response_id, sex, Q1, Q2) %>%
  srv_pivot_longer(c(Q1, Q2)) %>%
  rename(question = label) %>%
  group_by(sex, question) %>%
  summarise(percent_agree = mean(response == "Yes"), .groups = "drop") %>%
  ungroup()

dummy_survey_yn %>%
  g6tr_dodged_bar_plot(
    question, percent_agree, sex,
    flipped = TRUE
  )

Text on bars

The text marks with column values in most cases look good, although sometimes they need some fixes as e.g. in the plot above. g6tr bar plot functions provide some control over these marks via - set of text_* parameters, namely text_color, text_fontface, text_size and text_position - percent_digits parameter to set the number of decimal places to display in percentage values - label_threshold parameter to hide small values

Or you can completely remove the marks by setting text = FALSE.

As for the case of the plot above, we could for example set text_position to "beginning" and it will place the marks at the base of each bar. By default this parameter is set to "outside". In addition, let’s allow percentage accuracy to be defined automatically. This can be done by setting accuracy parameter to 0.1. In this case a heuristic is be used to ensure values have the minimum number of digits needed to show the difference between adjacent values.

dummy_survey_yn %>%
  g6tr_dodged_bar_plot(
    question, percent_agree, sex,
    flipped = TRUE,
    text_fontface = "plain",
    text_position = "beginning",
    accuracy = 0.1
  )

For stacked bar plots text can only be in the middle of bars.

dummy_survey %>%
  srv_prop_test_within(sex, Q3) %>%
  g6tr_stacked_bar_plot(
    sex, percentage, Q3,
    flipped = TRUE, text_color = "gray30",
    accuracy = 0.1
  )

Notice how one of the values doesn’t really fit inside it’s bar. Let’s hide it by setting label_threshold parameter.

dummy_survey %>%
  srv_prop_test_within(sex, Q3) %>%
  g6tr_stacked_bar_plot(
    sex, percentage, Q3,
    flipped = TRUE, text_color = "gray30",
    label_threshold = 0.05,
    accuracy = 0.1
  )

Displaying Proportion Test Results

To add some complexity to a bar plot you may want to display some additional information a function like srv_add_prop_test provides. Namely,

  • it is possible to display proportion confidence intervals via conf_int parameter, for this you point to a variable containing confidence interval error; this option is available for dodged bar plots only

  • you can mark proportions with significant p values (< 0.05) by setting the variable with p values to sig parameter

titanic_df %>%
  # dirty hack
  mutate(fake_pval = prop_pval / 2) %>%
  g6tr_dodged_bar_plot(
    Embarked, percentage, Sex,
    text_position = "middle", text_size = 5,
    conf_int = conf_int,
    sig = fake_pval
  )

Other Adjustments and Post Processing

Lastly, bar plot functions provide a set of additional parameters one may find useful when it’s needed to tweak appearance of a plot in some way. These are:

  • legend - to show (default) or hide the legend

  • bar_width - set a value from 0 to 1 to make bars thinner or thicker

  • wrap_length - if a cluster name exceeds this number of character, it will be attempted to break it into multiple lines

  • error_color - color of proportion test confidence intervals

  • color_scale - color palette that will be used for bar groups.

As for the last one, it is advised to use palette functions from this package, g6tr.theme. Let’s take a look at one particular example. We’ll simulate some data for a multiple choice survey.

library("forcats")

set.seed(1)
mc_survey_dummy_df <-
  expand.grid(
    question = paste("Question", 1:4),
    answer = c(
      "Strongly oppose", "Somewhat oppose",
      "Somewhat support", "Strongly support",
      "Unsure"
    )
  ) %>%
  mutate(p = runif(n(), 0.4, 1)) %>%
  group_by(question) %>%
  mutate(p = p / sum(p)) %>%
  mutate(question = fct_rev(question))

mc_survey_dummy_df %>% head()

[38;5;246m# A tibble: 6 × 3
[39m

[38;5;246m# Groups:   question [4]
[39m
  question   answer              p
  
[3m
[38;5;246m<fct>
[39m
[23m      
[3m
[38;5;246m<fct>
[39m
[23m           
[3m
[38;5;246m<dbl>
[39m
[23m

[38;5;250m1
[39m Question 1 Strongly oppose 0.160

[38;5;250m2
[39m Question 2 Strongly oppose 0.172

[38;5;250m3
[39m Question 3 Strongly oppose 0.200

[38;5;250m4
[39m Question 4 Strongly oppose 0.248

[38;5;250m5
[39m Question 1 Somewhat oppose 0.149

[38;5;250m6
[39m Question 2 Somewhat oppose 0.259

Our first attempt could be:

mc_survey_dummy_df %>%
  g6tr_stacked_bar_plot(
    question, p, answer,
    flipped = TRUE,
    text_size = 6
  )

Colors here look good, but since there is a clear linear order of answer options (strongly oppose - to - strongly support, + unsure) it’ll make much more sense to use a diverging color scale.

div_pal <- g6tr_pal_diverging("green_red", grey_pos = "first", n = 5, rev = TRUE)

p <-
  mc_survey_dummy_df %>%
  g6tr_stacked_bar_plot(
    question, p, answer,
    flipped = TRUE,
    text_size = 6,
    color_scale = div_pal
  )

p

To close it up, it is important to note that g6tr bar plot functions return ggplot objects and therefore they can be customized afterwards using ggplot2 functions like ggtitle, labs, theme, scale_* etc and g6tr custom themes as well.

library("ggplot2")

p +
  labs(x = NULL, y = NULL, title = "Survey Results") +
  theme_g6tr(base_size = 20)