Search code examples
rggplot2data-visualizationwaffle-chart

Waffle chart in R: Legend text merely consists of "A", "B", "C"; how to change?


I have this dataframe DF:

|total | n  |
|------|----|
| 0    | 19 |
| 1    | 16 |
| 2    | 23 |
| 3    | 31 |
| 4    | 20 |
| 5    | 95 |

... or, to make it reproducible:

> dput(DF)
structure(list(total = c(0, 1, 2, 3, 4, 5), n = c(19L, 16L, 23L, 
31L, 20L, 95L)), row.names = c(NA, 6L), class = "data.frame")

Now if I make a waffle chart out of it:

library(waffle)
waffle(DF$n, rows=6, size=0.6, 
       colors=c("#EAECEC", "#DFE0E2", "#B3B6BC", "#888D96", "#4E5656", 
                "#0A0B0B"), 
       #title="Legal Databases", 
       xlab="1 square == 1 country")

... I get a legend text consisting of "A", "B", "C" and so on:

Waffle chart with an ABC legend text

How can I change that legend text? I want it to read "Score: 0", "Score: 1" etc. until "Score: 5" instead of "A", "B", "C" etc.

I tried using the names()-solution from this post, but it didn't work.


Solution

  • Similar solution as akrun! In the documentation https://cran.r-project.org/web/packages/waffle/waffle.pdf there is the argument parts = named vector of values to use for the chart:

    library(waffle)
    parts=c(DF$n)
    names(parts) = paste0("Score: ", DF$total)
    waffle(parts, rows=6, size=0.6, 
           colors=c("#EAECEC", "#DFE0E2", "#B3B6BC", "#888D96", "#4E5656", 
                    "#0A0B0B"), 
           #title="Legal Databases", 
           xlab="1 square == 1 country")
    

    enter image description here