Skip to contents

Introduction

In this vignette, we show you how to use functions to create seven different chart types, to help you visualize your data: bar charts, diverging plots, dumbbell plots, heatmaps, scatter plots, line plots, and pyramid plots. They are (almost) presentation-ready charts with all of Gradient’s best practices applied.

These chart types are implemented in the following functions:

Creating Bar Charts

Let’s assume your first task is to to prepare a bar plot. You have to to deliver a graph that is publication-ready within a short timeframe. Luckily, you have access to the g6tr_bar_plot function, which will make it easy to create a professional-looking graph.

df <- titanic::titanic_test

df <- df %>%
  srv_add_prop_test(x = Sex, y = Embarked) %>% 
  count(Embarked, wt = n) %>% 
  mutate(perc = n / sum(n))

You load the necessary packages and data into R and call the g6tr_bar_plot() function. You pass in the data frame, x and y variables, and set the display_text argument to “all” to add text labels to all bars. You can sort the bars in descending order by setting the bar_order argument to “desc”.

Additionally, you can set the text_fontface to “bold” and also set the text_position to “outside” to ensure that the text labels are visible outside the bars.

df %>%
  g6tr_bar_plot(
   x = Embarked,
   y = perc,
   flipped = TRUE,
   display_text = "all",
   bar_order = "desc",
   text_fontface = 'bold',
   text_position = 'outside',
   text_size = 10
   ) +
   theme_g6tr()

If you want to highlight some specific bars in your bar plot, you can do so by setting the highlight argument to the specific items that you want to highlight (e.g., “Overall”). You can also choose to display only the labels of highlighted elements by setting the display_text argument to “highlighted”.

This will ensure that only the important bars are emphasized in your bar plot.

df %>%
  g6tr_bar_plot(
    x = Embarked,
    y = perc,
    flipped = TRUE,
    bar_order = "desc",
    display_text = "highlighted",
    text_fontface = 'bold',
    text_position = 'outside',
    text_size = 10,
    highlight = "Overall"
  ) +
theme_g6tr()

When you run the function again, the highlighted bars will appear in blue, and the non-highlighted bars will appear in grey. If you want to effectively convey important information to your readers, highlighting specific bars can be a useful technique.

Note:

  • Another way to use highlighting in bar plot like functions is to pass it in as a filter expression.

  • In order to pass in highlighting as a filter expression, you have to set highlight_condition to TRUE and use highlight as a filter expression.

df %>%
  g6tr_bar_plot(
    x = Embarked,
    y = perc,
    flipped = TRUE,
    bar_order = "desc",
    display_text = "highlighted",
    text_fontface = 'bold',
    text_position = 'outside',
    text_size = 10,
    highlight = "Embarked == 'Overall'",
    highlight_condition = TRUE
  ) +
  theme_g6tr()

Creating Diverging Plots

Your next task is to present a diverging plot for the next slide of the report.

sample_data <-
  tribble(
    ~x, ~y,
    ###########
    "Nike", .87,
    "Riley", .34,
    "Nissan", .98,
    "AT7", .76,
    "Cheggs", .56,
    "J&J", .67,
    "AAA", -.20,
    "Peach", -.40,
    "Can", -.50
  )

To present a diverging plot in your report, you can use the g6tr_diverging_plot() function, which is designed to create professional-looking diverging plots. Start by loading the necessary packages and data into R, and then call the g6tr_diverging_plot() function. Pass in the data frame (df), x and y variables.

Additionally, you can set the display_text argument to “all” to add text labels to all bars and the bar_order argument to “desc” to sort the bars in descending order.

This will help you create a clear and informative diverging plot.

Note: Setting the center argument to 0 will ensure that the plot originates from the center (0). Depending on your use case, feel free to adjust.

g6tr_diverging_plot(
  df = sample_data,
  x = x,
  y = y,
  center = 0,
  bar_order = "desc",
  display_text = "all",
  x_label_pos = "left",
  text_position = "inside",
  text_fontface = "bold",
  geom_type = "bar",
  text_color = "white"
) +
  labs(x = NULL, y = NULL)

If you want your plots to be in the form of a lollipop instead of bars, you can achieve this by changing the input of the argument geom_type. Instead of using “bar”, you can set it to “segment”. This will help you create the desired lollipop plot.

g6tr_diverging_plot(
  df = sample_data,
  x = x,
  y = y,
  bar_order = "desc",
  display_text = "all",
  x_label_pos = "left",
  text_position = "inside",
  text_fontface = "bold",
  geom_type = "segment",
  text_color = "white",
  text_size = 6
) +
  labs(x = NULL, y = NULL)

If you need to highlight certain attributes on your plot with different colours and display their labels outside, you can achieve this quickly by adding those attributes to the highlight argument. After that, update the bar_color and text_color arguments to reflect the new changes.

This will help you customize your plot and emphasize the important attributes with different colours and visible labels.

g6tr_diverging_plot(
  df = sample_data,
  x = x,
  y = y,
  bar_order = "desc",
  display_text = "all",
  point_size = 5,
  x_label_pos = "side",
  text_position = "outside",
  highlight = c("AT7", "AAA"),
  bar_color = c("#50bd90", "#EF8150"),
  bar_color_other = "#36c8ef",
  text_color = c("#50bd90", "#EF8150"),
  text_color_other = "#36c8ef",
  text_fontface = "bold",
  geom_type = "seg"
) +
  labs(x = NULL, y = NULL)

Creating Dumbbell Plots

Your next task is to produce a dumbbell plot to visualize the difference between estimated and actual car prices.

## Prepare sample data
set.seed(2022)
guess_master <-
  tibble(
    car_name = c("Acura", "Kia", "Nissan", "Porsche"),
    m2_actual = sample(1:100, 4),
    m2_guess = sample(1:100, 4),
    m2_past = sample(1:100, 4)
  )

If you want to create a professional-looking dumbbell plot, you can use the g6tr_dumbbell_plot() function, which simplifies the process for you. Begin by loading the necessary packages and data, and then call the g6tr_dumbbell_plot() function. Pass in the data frame (df), x values (x1 and x2), and y variables.

Note: Setting the xintercept argument to 50 would include a vertical line on the $50 mark on the x-axis. You can pass in a vector of numbers to the xintercept argument.

## Plot a basic dumbbell chart
guess_master %>%
  g6tr_dumbbell_plot(
    x1 = m2_actual,
    x2 = m2_guess,
    y = car_name,
    xintercept = 50,
    legend_labels = c("Actual", "Estimated"),
    scale = "dollar"
  )

If you want to add additional group for comparison (“past price”) to your dumbbell plot, you can do so by utilizing the g6tr_dumbbell_plot() function, which allows you to compare up to three groups.

To update your plot with an extra x argument (x3), simply pass in the additional values to the function.

Keep in mind that you’ll need to update the legend_labels argument to reflect the new groups, following the format (x1, x2, and/or x3). This will help you create a modified dumbbell plot that includes an additional group for comparison.

## Plot a basic dumbbell chart with all 3 X variables
guess_master %>%
  g6tr_dumbbell_plot(
    x1 = m2_actual,
    x2 = m2_guess,
    x3 = m2_past,
    y = car_name,
    xintercept = 50,
    legend_labels = c("Actual", "Estimated", "Past"),
    scale = "dollar"
  )

If you want to highlight specific elements (for example: Kia and Acura) on your plot and only display their text values, you can easily achieve this. To do so, simply set the highlight parameter to the targeted elements and set the display_text parameter to “highlighted”.

This will help you reduce the amount of text on the plot while still effectively conveying the necessary information.

## Plot dumbbell chart with highlighting features
guess_master %>%
  g6tr_dumbbell_plot(
    x1 = m2_actual,
    x2 = m2_guess,
    y = car_name,
    display_text = "highlighted",
    highlight = c("Kia", "Acura"),
    legend_labels = c("Actual", "Estimated"),
    scale = "dollar"
  )

Creating Heatmaps

Your next task is to visualize monthly sales figures across the years.

If you want to visualize monthly sales figures across multiple years in the form of a heatmap, you can use the g6tr_heatmap_plot() function. This function is a great option for visualizing large amounts of data in a clear and concise manner.

## Preparing test data set.

set.seed(4224)
sales_record <-
  expand_grid(
    month = factor(month.abb, levels = month.abb),
    year = factor(2016:2022)
  ) %>%
  mutate(
    value = sample(1:100, nrow(.), replace = TRUE) / 100,
    dollar_value = value * 124,
    dollar_label = dollar(value * 124, accuracy = 0.1)
  )

The initial heatmap plot shows the sales figures on a percentage scale with the year and month as the x and y-axis, respectively.

## Plot a heatmap without passing a custom label.
sales_record %>%
  g6tr_heatmap_plot(
    x = year,
    y = month,
    fill = value,
    scale = "percent",
    text_size = 5
  )

By setting the scale parameter to “custom” in the g6tr_heatmap_plot() function, the dollar value of the sales figures can be displayed as the fill color and custom dollar labels can be added to the plot.

You can use this feature to create a new heatmap plot with custom labels.

## Plot a heatmap with custom labels.
sales_record %>%
  g6tr_heatmap_plot(
    x = year,
    y = month,
    fill = dollar_value,
    custom_label = dollar_label,
    scale = "custom",
    text_size = 5
  ) 

You can also experiment with different ordering techniques to visualize the data better.

First, you can order the y-axis (month) by a particular level (2016) on the x-axis (year) to highlight the sales trend over the years.

sales_record %>%
  g6tr_heatmap_plot(
    x = year,
    y = month,
    fill = dollar_value,
    order_y_by = "2016",
    scale = scales::dollar,
    accuracy = 1,
    text_size = 5
  )

You can also order the x-axis (year) by a particular level (such as a specific month) on the y-axis (month).

sales_record %>%
  g6tr_heatmap_plot(
    x = year,
    y = month,
    fill = dollar_value,
    order_x_by = apply_desc("Dec"),
    scale = scales::dollar,
    accuracy = 1,
    text_size = 5
  )

Finally, to improve the visualization of the data, the x-axis (year) and y-axis (month) can both be ordered based on specific criteria.

The year can be ordered by a particular level (Dec) on the y-axis (month) in descending order, while the month can be ordered by a particular level (2016) on the x-axis (year).

sales_record %>%
  g6tr_heatmap_plot(
    x = year,
    y = month,
    fill = dollar_value,
    order_x_by = apply_desc("Dec"),
    order_y_by = "2016",
    scale = scales::dollar,
    accuracy = 1,
    text_size = 5
  )

Creating Scatter Plots

On the next slide, you have to create some scatter plots. Scatter plots are useful for plotting data points on a horizontal and a vertical axis to visualize the relationship between two variables. The plot can help you understand how one variable affects the other.

set.seed(21324)
sample_data <-
  tibble(
    consider = sample(1:100, 20) / 100,
    purchase = sample(1:100, 20) / 100,
    label = paste("Reason", sample(LETTERS, 20)),
    performance = sample(-100:100, 20) / 100,
    group = rep(c(
      "Asia", "Africa", "Europe", "N. America", "S.America"
    ), 4)
  )

To produce scatter plots with and without text labels, the g6tr_scatter_text_plot() and g6tr_scatter_point_plot() functions can come in handy for you.

To start off, you can plot purchase against consideration and add a label to the plot to give more meaning to the points on the scatter plot.

## Creating a basic scatter plot
# g6tr_scatter_text_plot(
#   df = sample_data,
#   x = consider,
#   y = purchase,
#   label = label,
#   color_scale = g6tr_pal("core")(1),
#   scale = "percent"
# )

Here’s how to replicate the plot without labels.

g6tr_scatter_point_plot(
  df = sample_data,
  x = consider,
  y = purchase,
  color_scale = g6tr_pal("core")(1),
  scale = "percent"
)

Next, if you need to highlight certain labels, you can use the highlight_condition argument in the g6tr_scatter_*_plot() functions.

This approach is different from what was done in previous functions, where a vector of elements to highlight was passed. Using a filter expression in the highlight_condition argument allows for highlighting to depend on various factors/variables present in the data, making it a convenient option.

# g6tr_scatter_text_plot(
#   df = sample_data,
#   x = consider,
#   y = purchase,
#   label = label,
#   highlight_condition = "consider > 0.5 & purchase > 0.5 & group == 'Asia'",
#   include_point = TRUE,
#   x_intercept = 0.5,
#   y_intercept = 0.5,
#   scale = "percent"
# )

Here’s how to replicate the plot without labels.

g6tr_scatter_point_plot(
  df = sample_data,
  x = consider,
  y = purchase,
  highlight_condition = "consider > 0.5 & purchase > 0.5 & group == 'Asia'",
  x_intercept = 0.5,
  y_intercept = 0.5,
  scale = "percent"
)

Note:

  • The other highlighting method shown in previous functions still works in the function.

  • In this case, you pass them in the highlight argument.

  • highlight and highlight_condition can’t both be present in the function. i.e one must be set to NULL.

  • For highlight to work, a value must be passed to the label argument.

g6tr_scatter_point_plot(
  df = sample_data,
  x = consider,
  y = purchase,
  label = label,
  highlight = c("Reason G", "Reason A"),
  x_intercept = 0.5,
  y_intercept = 0.5,
  scale = "percent"
)

Creating Line Plots

Your next task is to visualize trends across time for different statements. The best way to do this is to produce a line plot and you can do that with the aid of the g6tr_line_plot() function.

# Prepare fake data
x_duration <- c(
  "June 2020",
  "October 2020",
  "June 2021",
  "November 2021",
  "April 2022",
  "September 2022"
)

set.seed(2132)

sample_lp_data <-
  expand_grid(
    duration = factor(x_duration, levels = x_duration),
    levels = c(
      "Support: Increasing housing density",
      "Oppose: Increasing housing density",
      "No Opinion: Increasing housing density",
      "Support: Ending parking requirements",
      "Oppose: Ending parking requirements",
      "No Opinion: Ending parking requirements"
    )
  ) %>%
  mutate(
    perc_agree =
      case_when(
        str_detect(levels, "^Support") ~
          sample(45:60, nrow(.), replace = TRUE) / 100,
        str_detect(levels, "^Oppose") ~
          sample(20:30, nrow(.), replace = TRUE) / 100,
        TRUE ~ sample(5:10, nrow(.), replace = TRUE) / 100
      )
  ) %>%
  mutate(conf_int = sample(1:7, nrow(.), replace = TRUE) / 100)

You can pass in the prepared data set and required fields in the x ,y and group arguments. To create some space between each point on the plot, you can add points to the n_insert argument .

sample_lp_data %>%
  g6tr_line_plot(
    x = duration,
    y = perc_agree,
    group = levels,
    conf_int = conf_int,
    include_point = TRUE,
    n_insert = 10,
    n_border = 1,
    x_wrap = 6
  ) +
  guides(
    group = guide_legend(ncol = 1),
    color = guide_legend(ncol = 1)
  )

As with all functions described here, the highlighting functionality is a shared characteristic.

If you need to only highlight the group that supported an Increase in housing density in the plot. By setting display_text = "highlighted" and highlight = "Support: Increasing housing density", that can be achievable.

sample_lp_data %>%
  g6tr_line_plot(
    x = duration,
    y = perc_agree,
    group = levels,
    conf_int = conf_int,
    include_point = TRUE,
    display_text = "highlighted",
    highlight = "Support: Increasing housing density",
    n_insert = 10,
    n_border = 1,
    x_wrap = 6
  ) +
   guides(
    group = guide_legend(ncol = 1),
    color = guide_legend(ncol = 1)
  )

Finally, you might want to highlight groups that all had agreement of above 20%. This isn’t an easy task when using the highlight condition so instead, you can pass in a highlight condition to the highlight_condition argument.

sample_lp_data %>%
  g6tr_line_plot(
    x = duration,
    y = perc_agree,
    group = levels,
    conf_int = conf_int,
    include_point = TRUE,
    display_text = "highlighted",
    highlight_condition = "all(perc_agree > 0.2)",
    n_insert = 10,
    n_border = 1,
    x_wrap = 6
  ) +
   guides(
    group = guide_legend(ncol = 1),
    color = guide_legend(ncol = 1)
  )

Note:

  • all() in the highlight condition is checking that across time, perc_agree is above 20%.

  • Setting the highlight condition without all() would pick any other group that had at least one record of an agreement of over 20%.

sample_lp_data %>%
  g6tr_line_plot(
    x = duration,
    y = perc_agree,
    group = levels,
    conf_int = conf_int,
    include_point = TRUE,
    display_text = "highlighted",
    highlight_condition = "perc_agree > 0.2",
    n_insert = 10,
    n_border = 1,
    x_wrap = 6
  ) +
   guides(
    group = guide_legend(ncol = 1),
    color = guide_legend(ncol = 1)
  )

Creating Pyramid Plots

A useful way to compare and contrast between different sets of data is to create pyramid plots. In g6tr.theme, there are two versions of pyramid plots available:

Both options are useful, but g6tr_pyramid_plot() offers more customization options after the plot is created.

set.seed(13424)
sample_data <-
  tibble(continent = c("Africa", "Asia", "Europe", "N'America", "S'America")) %>%
  mutate(perc_sea = sample(1:100, nrow(.)) / 100) %>%
  mutate(perc_land = sample(1:100, nrow(.)) / 100)

sample_data_2 <-
  sample_data %>%
  tidyr::pivot_longer(cols = starts_with("perc")) %>%
  mutate(across(c("continent", "name"), factor))

facet_labels <- c(perc_land = "Land", perc_sea = "Sea")

g6tr_pyramid_plot()

To create a basic patchwork pyramid plot, you will need to provide the required arguments: dataframe, x, y, group and facet_labs. To customize the ordering of the plot, you can specify which of the bars should the plot be ordered by (order_by = perc_land).

sample_data_2 %>%
  g6tr_pyramid_plot(
    x = continent,
    y = value,
    group = name,
    order_by = "perc_land",
    bar_order = "desc",
    facet_labs = facet_labels,
    text_position = "outside",
    text_color = "black"
  )

The pyramid plot can also be reversed by setting plot_style = "reversed".

sample_data_2 %>%
  g6tr_pyramid_plot(
    x = continent,
    y = value,
    group = name,
    order_by = "perc_land",
    bar_order = "desc",
    facet_labs = facet_labels,
    text_position = "outside",
    plot_style = "reversed"
  )

Passing highlights as filter expression can really taking highlighting to another level in this functions.

Take a look at the following:

sample_data_2 %>%
  g6tr_pyramid_plot(
    x = continent,
    y = value,
    group = name,
    order_by = "perc_land",
    bar_order = "desc",
    facet_labs = facet_labels,
    text_position = "outside",
    text_color = "black",
    highlight = "name == 'perc_sea'",
    bar_color = "red",
    bar_color_other = "blue"
  )

facet_labels_b <- c(perc_sea = "Sea", perc_land = "Land")

filter_expr <-
  "(name == 'perc_land' & continent %in% c('Europe', 'Africa')) |
(name == 'perc_sea' & stringr::str_detect(continent, 'America'))"

sample_data_2 %>%
  g6tr_pyramid_plot(
    x = continent,
    y = value,
    group = name,
    order_by = "perc_sea",
    facet_labs = facet_labels_b,
    bar_order = "desc",
    plot_style = "pyramid",
    display_text = "highlighted",
    highlight = filter_expr,
    label_threshold = 0.15
  )

Note:

  • The facet_labs argument of g6tr_pyramid_plot() has to be a named vector of length 2.

  • names(facet_labs) has to correspond to the distinct values in group.

g6tr_pyramid_plot_2()

To create a basic patchwork pyramid plot, you will need to provide the required arguments: dataframe, x, y1, and y2. To customize the ordering of the plot, you can specify which of the bars should the plot be ordered by (order_by = perc_sea).

sample_data %>%
  g6tr_pyramid_plot_2(
    x = continent,
    y1 = perc_sea,
    y2 = perc_land,
    order_by = perc_sea,
    bar_order = "desc",
    text_position = "end",
    label_threshold = 0.15
  )

The pyramid plot can also be reversed by setting plot_style = "reversed".

sample_data %>%
  g6tr_pyramid_plot_2(
    x = continent,
    y1 = perc_sea,
    y2 = perc_land,
    order_by = perc_sea,
    bar_order = "asc",
    plot_style = "reversed",
    text_position = "end",
    bar_color = g6tr_pal("core")(5)[2],
    label_threshold = 0.15
  )

Highlighting in g6tr_pyramid_plot_2() works slightly differently compared to other bar plot types. To highlight a particular element, the argument highlight should be passed to the function with the desired element to highlight.

However, it’s worth noting that this parameter is duplicated to serve both bar plots (left and right) at the backend.

sample_data %>%
  g6tr_pyramid_plot_2(
    x = continent,
    y1 = perc_sea,
    y2 = perc_land,
    order_by = perc_sea,
    bar_order = "desc",
    plot_style = "pyramid",
    plot_labels = c("Sea", "Land"),
    display_text = "highlighted",
    title = "Difference in land and sea coverage",
    highlight = "Europe",
    bar_color = g6tr_pal("core")(5)[2],
    text_position = "end",
    label_threshold = 0.15
  )

Note:

  • What this means is that, it is possible to highlight different things in both bar plots.

  • To do this, pay attention to the highlight argument below.

  • highlight in this case would be a named list. The names of this list MUST be y1 and y2.

  • The same applies to bar_color.

 sample_data %>%
  g6tr_pyramid_plot_2(
    x = continent,
    y1 = perc_sea,
    y2 = perc_land,
    order_by = perc_sea,
    bar_order = "desc",
    plot_style = "pyramid",
    plot_labels = c("Sea", "Land"),
    display_text = "highlighted",
    title = "Difference in land and sea coverage",
    highlight = list(y1 = sample_data$continent[1:3],
                     y2 = sample_data$continent[3:5]),
    bar_color = list(y1 = g6tr_pal("core")(5)[2],
                     y2 = g6tr_pal("core")(5)[3]),
    text_position = "end",
    label_threshold = 0.15
  )

Finally, if you need to differentiate the two plots with colours. Passing a list of colours to bar_color will do the trick.

sample_data %>%
  g6tr_pyramid_plot_2(
    x = continent,
    y1 = perc_sea,
    y2 = perc_land,
    order_by = perc_sea,
    bar_order = "desc",
    plot_style = "pyramid",
    plot_labels = c("Sea", "Land"),
    display_text = "highlighted",
    title = "Difference in land and sea coverage",
    bar_color = list(y1 = g6tr_pal("core")(5)[2],
                     y2 = g6tr_pal("core")(5)[3]),
    text_position = "end",
    label_threshold = 0.15
  )