2

I'm creating a barplot using ggplot2 where each bar represents a country. I would like the fill of each bar to be the country's flag for easy identification.

Here's a simple example

library("ggplot2")
DF <- data.frame(country = c("UK", "France", "Germany"), 
                 value=c(4, 3, 7))
ggplot(DF, aes(x=country, y=value, fill="#f00")) + geom_bar(stat="identity")

Instead of red bars I would like the bars to be coloured/images of flags. Does anyone have ideas/suggestions for doing this?

smci
  • 32,567
  • 20
  • 113
  • 146
ekstroem
  • 5,957
  • 3
  • 22
  • 48
  • Not sure if bars can be filled using images, but you can label with a flag using `ggimage`. See [the vignette](https://cran.r-project.org/web/packages/ggimage/vignettes/ggimage.html) and look for `geom_flag`. – neilfws May 16 '18 at 22:47
  • 1
    I don't agree that this question is a duplicate of the question linked. The question linked _does not_ teach a method for filling a bar with an image, it teaches a method for filling the entire plot area with an image and covering up certain portions. – mac Nov 09 '18 at 20:24

1 Answers1

3

The possible approach here is for a scatter plot, not a bar plot - still I hope you find it helpful. The ggflags package (https://github.com/YTLogos/ggflags) geom_flag displays a circular, sizeable flag image using ggplot aesthetics x, y and country.

devtools::install_github("YTLogos/ggflags") 

library("ggplot2")
library(ggflags)
DF <- data.frame(country = c("UK", "France", "Germany"), 
                 value=c(4, 3, 7))
ggplot(DF, aes(x=country, country=country, y=value)) + geom_flag(size = 10)

A static size of 10 is chose here just for visibility but it can be a variable size as well.

John Walker
  • 191
  • 5
  • That is actually quite nice. Wasn't exactly what I had in mind but it does allow me to put flags on top of the bars for easy identification. Thanks! – ekstroem May 18 '18 at 22:52