Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

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).

like image 521
user3542212 Avatar asked Jul 04 '19 10:07

user3542212


People also ask

What Ggplot Geom function would you use to create a bar graph?

There are two types of bar charts: geom_bar() and geom_col() . geom_bar() makes the height of the bar proportional to the number of cases in each group (or if the weight aesthetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use geom_col() instead.


2 Answers

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

like image 140
Maurits Evers Avatar answered Oct 19 '22 17:10

Maurits Evers


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)

like image 3
Mikko Marttila Avatar answered Oct 19 '22 19:10

Mikko Marttila