Skip to content
Permalink
Fetching contributors…
Cannot retrieve contributors at this time
116 lines (99 sloc) 3.86 KB
---
title: '{ggtext} for images as x-axis labels'
author: Jonathan Carroll
date: '2019-08-13'
slug: ggtext-for-images-as-x-axis-labels
categories:
- R
tags:
- ggplot2
- rstats
type: ''
subtitle: ''
image: ''
---
```{r, setup, include = FALSE}
library(ggplot2)
library(ggtext)
library(rvest)
knitr::opts_chunk$set(
class.output = "bg-success",
class.message = "bg-info text-info",
class.warning = "bg-warning text-warning",
class.error = "bg-danger text-danger"
)
```
I've written [a](https://jcarroll.com.au/2016/06/02/images-as-x-axis-labels/)
[few](https://jcarroll.com.au/2016/06/03/images-as-x-axis-labels-updated/)
[times](https://jcarroll.com.au/2018/10/16/even-more-images-as-x-axis-labels/)
about using an image as an x-axis label, and the solutions have been slowly
improving. This one blows all of them out of the water.
<!--more-->
I've written [a](https://jcarroll.com.au/2016/06/02/images-as-x-axis-labels/)
[few](https://jcarroll.com.au/2016/06/03/images-as-x-axis-labels-updated/)
[times](https://jcarroll.com.au/2018/10/16/even-more-images-as-x-axis-labels/)
about using an image as an x-axis label, and the solutions have been slowly
improving. This one blows all of them out of the water.
[Claus Wilke](https://github.com/clauswilke) ([\@ClausWilke](https://twitter.com/ClausWilke))
now has a [{ggtext}](https://github.com/clauswilke/ggtext) package which can very
neatly add images as x-axis labels!
This makes the solution as simple as
```{r, fig.cap = "{ggtext} makes this easy!"}
library(ggplot2)
library(ggtext)
library(rvest)
## GDP per capita, top 11 countries
url <- "https://en.wikipedia.org/wiki/List_of_countries_by_GDP_(nominal)_per_capita"
html <- xml2::read_html(url)
gdppc <- html_table(html_nodes(html, "table")[3])[[1]][1:11,]
## clean up; remove non-ASCII and perform type conversions
gdppc$Country <- gsub("Â ", "", gdppc$Country)
gdppc$Country <- iconv(gdppc$Country, "latin1", "ASCII", sub="")
gdppc$Country[9] <- "United States of America"
gdppc$Rank <- iconv(gdppc$Rank, "latin1", "ASCII", sub="")
gdppc$`US$` <- as.integer(sub(",", "", gdppc$`US$`))
## switching to a different source of flag images
labels <- setNames(
paste0("<img src='http://www.senojflags.com/images/country-flag-icons/",
gsub(" ", "-", gdppc$Country), "-Flag.png' width='30' /><br>",
sapply(strwrap(gdppc$Country, width = 10, simplify = FALSE),
function(x) paste(x, collapse = "<br>"))),
gdppc$Country
)
## create a dummy dataset
npoints <- length(gdppc$Country)
y <- gdppc$`US$`
x <- gdppc$Country
dat <- data.frame(x=factor(x, levels=gdppc$Country), y=y)
## NB: #85bb65 is the color of money in the USA apparently.
gg <- ggplot(dat, aes(x=x, y=y/1e3L, group=1))
gg <- gg + geom_bar(col="black", fill="#85bb65", stat="identity")
gg <- gg + scale_x_discrete(name = NULL, labels = labels)
gg <- gg + theme_minimal()
gg <- gg + scale_fill_discrete(guide=FALSE)
gg <- gg + theme(plot.background = element_rect(fill="grey90"))
gg <- gg + labs(title="GDP per capita",
subtitle="Top 11 countries",
x="", y="$US/1000",
caption=paste0("Source: ",url))
## ggtext::element_markdown
gg <- gg + theme(axis.text.x = element_markdown(color = "black", size = 7),
axis.text.y = element_text(size=14),
axis.title.x = element_blank())
gg
```
This is an even nicer solution than I've been using, not only because it's shorter
to use, but also more flexible - markdown can be processed (using `element_markdown`)
wherever `element_text` is used, such as axis text, legends, titles, etc...
I think this finally closes this chapter, but now it's time to make some really cool
graphs with images.
<br />
<details>
<summary>
<tt>devtools::session_info()</tt>
</summary>
```{r sessionInfo, echo = FALSE}
devtools::session_info()
```
</details>
<br />
You can’t perform that action at this time.