user3542212
user3542212

Reputation: 111

How can I create a "progress bar" type of graph in ggplot2 to display the percentile that a person is in?

I am trying to generate a one-dimensional graph that looks like a progress bar in that it gets filled up depending on which percentile a subject falls in.

enter image description here

I have the percentile as a numerical value, just don't know how to graph it to look look like a horizontal bar that is filled according to the percentile (0-100).

Upvotes: 7

Views: 2738

Answers (2)

Mikko Marttila
Mikko Marttila

Reputation: 11908

Minimally, you can plot a total bar, overlay the percentile bar, and then turn the plot horizontally:

library(ggplot2)

percentile <- 12

ggplot() +
  geom_col(aes("", 100)) +
  geom_col(aes("", percentile), fill = "forestgreen") +
  coord_flip()

Created on 2019-07-04 by the reprex package (v0.3.0)

Upvotes: 3

Maurits Evers
Maurits Evers

Reputation: 50718

Here is something that might get you started.

First off, let's generate some minimal sample data

df <- data.frame(
    Extraversion = 12,
    Intraversion = 40)

We then reshape the data and add a total 100% column

library(tidyverse)
df <- df %>%
    gather(key, val) %>%
    mutate(
        key = factor(key, rev(unique(key))),
        Total = 100)

We define a convenience function that produces the text inside the "progress bar"

format_value <- function(key, val) {
    qual <- c("very low", "low", "average", "high", "very high", "max")
    sprintf(
        "%s - %ith percentile - %s",
        key, val, qual[findInterval(val, seq(0, 100, by = 20))])
}

Now we're ready to plot

ggplot(df, aes(key, val)) +
    geom_col(fill = "forestgreen") +
    geom_col(aes(y = Total), alpha = 0.5, colour = "black") +
    geom_text(
        aes(y = 5, label = format_value(key, val)),
        hjust = 0,
        fontface = "bold",
        colour = "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())

enter image description here

Upvotes: 6

Related Questions