Accessibility Web Development – How to Make R Shiny Apps Accessible

[This article was first published on Tag: r - Appsilon | Enterprise R Shiny Dashboards, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Accessibility Web Development Article Thumbnail

It’s crucial you address R Shiny accessibility early on. Why? Because you want to make sure your data products can be used by all users – inclusivity matters. In a nutshell, that’s what web accessibility development means, but you’ll learn more about it in the context of R Shiny apps today.

To kick things off, we’ll start with the theory behind R Shiny accessibility and web accessibility in general. There are some, somewhat strict rules you need to follow if you want to provide the most inclusive user experience.

Want to see how users use your R Shiny dashboard? Here are three tools for monitoring user adoption.

Table of contents:


Web Accessibility Theory Explained

As mentioned earlier, accessibility means your data products (e.g., dashboards) can be used equally by all users. To get started, you should look no further than the A11Y project. The term “A11Y” is an abbreviation of the word “accessibility,” because there are 11 letters between A and Y.

The entire project breaks down accessibility into a checklist anyone can follow. Let’s go over a couple of their points.

Don’t rely on color to explain the data

Some people are color-blind, so a stacked bar chart with each category represented by a different color doesn’t always translate. Also, your charts can be printed in a black and white color scheme, making the coloring super confusing.

The ggpattern R package can help. To demonstrate, we’ll copy a stacked bar chart source code from the ggplot2 example gallery and compare the two libraries. The code snippet below creates a traditional stacked bar chart, where each colored segment of a bar represents one category:

library(ggplot2)

specie <- c(rep("sorgho", 3), rep("poacee", 3), rep("banana", 3), rep("triticum", 3))
condition <- rep(c("normal", "stress", "Nitrogen"), 4)
value <- abs(rnorm(12, 0, 15))
data <- data.frame(specie, condition, value)

ggplot(data, aes(fill = condition, y = value, x = specie)) +
    geom_bar(position = "stack", stat = "identity")
Image 1 - ggplot2 stacked bar chart

Image 1 – ggplot2 stacked bar chart

Just imagine if you were color-blind – it would be either extremely difficult or impossible to distinguish between the categories. That’s why adding patterns is helpful. The following code snippet adds a distinct pattern to each category:

library(ggpattern)

ggplot(data, aes(fill = condition, y = value, x = specie)) +
    geom_col_pattern(
        aes(pattern = condition, fill = condition, pattern_fill = condition),
        colour = "black",
        pattern_colour = "white",
        pattern_density = 0.15,
        pattern_key_scale_factor = 1.3
    )
Image 2 - ggpattern stacked bar chart

Image 2 – ggpattern stacked bar chart

It doesn’t matter if you can’t tell the difference between colors, or if the chart gets printed in shades of gray – everyone can spot a pattern and identify the individual categories.

Want to expand your bar charts skills in ggplot2? Check out our guide to bar charts and try to make them more accessible.

Don’t use very bright or low-contrast colors

Your background and foreground colors should be different enough. But what classifies as enough? That can be tricky to decide.

Luckily, free online tools such as contrastchecker.com allow you to verify if your colors pass the tests. There are six tests on the website currently. Don’t worry about what they mean, just remember that green is good, and red is bad.

Here’s an example. A white background color with black text is clear and easy for everyone to see:

Image 3 - Contrast checker - white and black

Image 3 – Contrast checker – white and black

Black and white are the exact opposite colors, so the human eye has little difficulty identifying the characters. But what about yellow letters on a white background? Let’s see:

Image 4 - Contrast checker - white and yellow

Image 4 – Contrast checker – white and yellow

Suddenly, things went south. Reading the yellow text on a white background causes your eyes to strain. It’s difficult even with typical color perception. For that reason, all of the six tests have failed.

Don’t overwhelm the user with the information

If you’re a statistician or a data scientist, it’s easy to think everyone will understand your dashboards just because you do. It’s a common fallacy. But the reality is most users are not following your internal logic.

Don’t include dozens of charts on a single dashboard page! It’s a bad design practice that will leave your users confused, concerned, and likely disoriented. Make one chart a focus of the dashboard and add a couple of helper charts around it. That’s enough. If you can’t convey a message with a handful of data visualizations, consider simplifying your message or re-evaluate your approach.

Also, you should use consistent language and color. If charts have identical X-axis, you shouldn’t name it differently across plots. Likewise, using red and blue in one chart and green and yellow on the other is just confusing, especially if the chart types are identical. Be consistent!

Translate the data into clear language

Every data visualization can be simplified. But you don’t have to remove elements to simplify things – you can also add to simplify.

Even if the chart looks simple enough to you, you can simplify it further by providing additional information. The ggplot2 R package allows you to easily add titles, and subtitles, but that’s only the starting point.

Let’s take a look at the following visualization. It’s sort of a progress bar, and it shows how many users have registered to the company’s newsletter as of 2022/05/15 vs. how many registrations the company needs:

library(ggplot2)

registered_users <- 559
target_users <- 1500

ggplot() + 
    geom_col(aes("", target_users), alpha = 0.5, color = "black") + 
    geom_col(aes("", registered_users), fill = "#0199f8") + 
    coord_flip() + 
    ggtitle("Number of user registrations vs. the target")
Image 5 - A bad example of a progress bar

Image 5 – A bad example of a progress bar

There are many things wrong with this visualization. For starters, it’s near impossible to read how many users have registered so far. We also don’t know up to which date the chart shows data, nor what the data really represents. We know these are registrations, but for what?

Always provide additional context! It makes the data interpretation clearer and more accessible. Here’s an example:

library(ggplot2)

registered_users <- 559
target_users <- 1500

format_text <- function(registered, target) {
    pct <- round((registered / target) * 100, 2)
    paste0(registered, "/", target, " users registered - ", pct, "%")
}

ggplot() +
    geom_col(aes("", target_users), alpha = 0.5, color = "black") +
    geom_col(aes("", registered_users), fill = "#0199f8") +
    geom_text(
        aes("", y = 65, label = format_text(registered_users, target_users)),
        hjust = 0,
        fontface = "bold",
        size = 10,
        color = "white"
    ) +
    coord_flip() +
    theme_minimal() +
    theme(
        axis.title = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.background = element_blank()
    ) +
    labs(
        title = "Number of user registrations vs. the target",
        subtitle = paste0("As of 2022/05/15, ", registered_users, " users have registered for our company's weekly newsletter. Our target is ", target_users, " and we plan to achieve it by the end of the year.")
    )
Image 6 - A good example of a progress bar

Image 6 – A good example of a progress bar

Other A11Y guidelines

We’ll only cover a handful of A11Y guidelines. But there’s an exhaustive checklist you can find and follow on their website, and we encourage you to do so.

In general, here are guidelines you should remember about R Shiny accessibility. We gathered them from an RStudio Meetup on data visualization accessibility presented by two advocates and contributors to the R and Shiny community, Maya Gans and Mara Averick. We recommend you watch the video, you’ll even catch some of these points put into action in the presentations:

  • Don’t rely on color to explain the data. Use chart patterns as we explained earlier.
  • Don’t use very bright or low-contrast colors. It just looks bad and in some cases makes it impossible to read the text.
  • Don’t hide important data behind interactions. Hover events aren’t possible on mobile, and most users will access your dashboard from a smartphone.
  • Don’t overwhelm users with the information. Showing 500 charts on a single dashboard page is just awful.
  • Use accessibility tools when designing. Google Lighthouse and the A11Y project checklist are good places to start.
  • Use labels and legends. Otherwise, how will the user know what the data represents?
  • Translate the data into clear language. Every chart can be simplified. Make sure you have your target user in mind.
  • Provide context and explain the visualization. Annotate individual data points on a chart (e.g., all-time high, all-time low, dates).
  • Focus on accessibility during user interviews. Create narratives of people who will use the app. Person X in HR will use the dashboard differently than Person Y, the CFO.

Now you know the theory, so next, we’ll see how accessibility translates to R Shiny.

A11Y and Shiny – Get Started with R Shiny accessibility

Here’s the good news – you don’t need to lift a finger regarding R Shiny accessibility, as someone already did all the heavy lifting for you. The shinya11y package is a huge time saver, and comes will every A11Y guideline and checklist. The best part? It integrates seamlessly into your Shiny apps.

To start, let’s install the package:

devtools::install_github("ewenme/shinya11y")

You can launch the demo Shiny app from the R console to get the gist of it:

shinya11y::demo_tota11y()
Image 7 - Demo shinya11y app

Image 7 – Demo shinya11y app

The button on the bottom left corner of the app allows you to toggle various checklists. You can, for example, see if your app breaks one or more A11Y rules for accessibility. If a highlighted portion is red, you know there’s something you’ll need to address.

But the best part about the package is that you can easily integrate it into your own R Shiny apps.

For demonstration, we’ll reuse an R Shiny application from our Tools for Monitoring User Adoption article. The dashboard applies a clustering algorithm to the Iris dataset and lets you change the columns you want to see on a scatter plot:

library(shiny)

ui <- fluidPage(
    headerPanel("Iris k-means clustering"),
    sidebarLayout(
        sidebarPanel(
            selectInput(
                    inputId = "xcol",
                    label = "X Variable",
                    choices = names(iris)
                ),
            selectInput(
                    inputId = "ycol",
                    label = "Y Variable",
                    choices = names(iris),
                    selected = names(iris)[[2]]
                ),
            numericInput(
                inputId = "clusters",
                label = "Cluster count",
                value = 3,
                min = 1,
                max = 9
            )
        ),
        mainPanel(
            plotOutput("plot1")
        )
    )
)

server <- function(input, output, session) {
    selectedData <- reactive({
        iris[, c(input$xcol, input$ycol)]
    })
    clusters <- reactive({
        kmeans(selectedData(), input$clusters)
    })
    output$plot1 <- renderPlot({
        palette(c(
            "#E41A1C", "#377EB8", "#4DAF4A", "#984EA3",
            "#FF7F00", "#FFFF33", "#A65628", "#F781BF", "#999999"
        ))
        
        par(mar = c(5.1, 4.1, 0, 1))
        plot(selectedData(),
                col = clusters()$cluster,
                pch = 20, cex = 3
        )
        points(clusters()$centers, pch = 4, cex = 4, lwd = 4)
    })
}

shinyApp(ui = ui, server = server)
Image 8 - Clustering R Shiny application

Image 8 – Clustering R Shiny application

To add shinya11y, you’ll need to modify two things:

  1. Import the shinya11y library.
  2. Add a call to use_tota11y() at the top of Shiny UI.

Here’s what the modified app looks like in code:

library(shiny)
library(shinya11y)

ui <- fluidPage(
    use_tota11y(),
    headerPanel("Iris k-means clustering"),
    sidebarLayout(
        sidebarPanel(
            selectInput(
                inputId = "xcol",
                label = "X Variable",
                choices = names(iris)
                ),
            selectInput(
                inputId = "ycol",
                label = "Y Variable",
                choices = names(iris),
                selected = names(iris)[[2]]
                ),
            numericInput(
                inputId = "clusters",
                label = "Cluster count",
                value = 3,
                min = 1,
                max = 9
            )
        ),
        mainPanel(
            plotOutput("plot1")
        )
    )
)

server <- function(input, output, session) {
    selectedData <- reactive({
        iris[, c(input$xcol, input$ycol)]
    })
    clusters <- reactive({
        kmeans(selectedData(), input$clusters)
    })
    output$plot1 <- renderPlot({
        palette(c(
            "#E41A1C", "#377EB8", "#4DAF4A", "#984EA3",
            "#FF7F00", "#FFFF33", "#A65628", "#F781BF", "#999999"
        ))
        
        par(mar = c(5.1, 4.1, 0, 1))
        plot(selectedData(),
                col = clusters()$cluster,
                pch = 20, cex = 3
        )
        points(clusters()$centers, pch = 4, cex = 4, lwd = 4)
    })
}

shinyApp(ui = ui, server = server)

And here’s what it looks like when launched:

Image 9 - Clustering R Shiny application with accessibility tools

Image 9 – Clustering R Shiny application with accessibility tools

It really is that simple. You can now add these two lines to any existing Shiny app and see if there’s anything that needs improvement.


Summary of Web Accessibility Development for R Shiny Accessibility

If you’re just starting out, accessibility might be tough to wrap your head around. It’s easy to neglect some rules and guidelines if you don’t experience the same challenges others face. But if you go the extra mile, you’ll ensure that your Shiny app, data visualization, or presentation, will be inclusive.

We believe building tech solutions should be no different than any other engineering project; it should be inviting, accessible to all, and provide high-quality service to every user.

Now it’s time for you to shine. For a homework assignment, pick up any of your R Shiny dashboards and plug in the shinya11y package. See what needs addressing and make sure to do so. If you’re ready, share your results with us on Twitter – @appsilon. We’d love to see how accessible Shiny can become.

Ready to take your data visualization skills to the next level? Here are 5 key data visualization principles you must know.

Additional Resources for Accessible Color and Design

Additional resources to help you create accessible visualizations for color Blindness:

The post Accessibility Web Development – How to Make R Shiny Apps Accessible appeared first on Appsilon | Enterprise R Shiny Dashboards.

To leave a comment for the author, please follow the link and comment on their blog: Tag: r - Appsilon | Enterprise R Shiny Dashboards.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)