| title |
descriptionMeta |
descriptionTop |
sectionText |
sectionLink |
DataToVizText |
DataToVizLink |
url |
output |
Donut chart with ggplot2 |
The ggplot2 package allows to build donut chart with R. This post describes how, providing explanation and reproducible code. |
The ggplot2 package allows to build donut chart with R. This post describes how, providing explanation and reproducible code. |
Donut section |
doughnut-plot.html |
Warning |
data-to-viz.com/caveat/pie.html |
128-ring-or-donut-plot |
| html_document |
| self_contained |
mathjax |
lib_dir |
template |
css |
toc |
toc_float |
toc_depth |
df_print |
false |
default |
libs |
template_rgg.html |
style.css |
true |
true |
2 |
paged |
|
|
```{r global options, include = FALSE}
knitr::opts_chunk$set( warning=FALSE, message=FALSE)
```
# Most basic doughnut chart with `ggplot2`
***
The `ggplot2` package allows to build [donut charts](doughnut-plot.html). Note however that this is possible thanks a hack, since no specific function has been created for this kind of chart. (This is voluntary, to avoid donut charts that are dataviz [bad practice](https://www.data-to-viz.com/caveat/pie.html))
Here is the process:
- input data provides a numeric variable for a set of entities
- absolute numeric values must be translated to proportion
- group positions must be stacked: we're gonna display them one after the other
- `geom_rect()` is used to plot each group as a rectangle
- `coord_polar()` is used to switch from stacked rectangles to a ring
- `xlim()` allows to switch from pie to donut: it adds the empty circle in the middle
```{r thecode, echo=FALSE, out.width = "100%", fig.height=7}
# load library
library(ggplot2)
# Create test data.
data
```{r thecode, eval=FALSE}
```
# Customization
***
Here are a couple of things you can do improve your donut chart style:
- use `theme_void()` to get rid of the unnecessary background, axis, labels and so on.
- use a better color palette
- don't use a legend, add labels to groups directly
```{r thecode3, echo=FALSE, out.width = "100%", fig.height=7}
# load library
library(ggplot2)
# Create test data.
data
```{r thecode3, eval=FALSE}
```
# Donut thickness
***
It is important to understand that donut chart are just stacked rectangles that are made circular thanks to `coord_polar`.
Thus, the empty circle that makes it a donut chart is just the space between the initial Y axis and the left part of the rectangle.
- If `xlim` left boundary is big, no empty circle. You get a pie chart
- If `xlim` is low, the ring becomes thinner.
If you don't get it, just plot the chart without `coord_polar()`
```{r thecode2, echo=FALSE, out.width = "100%", fig.height=7}
# load library
library(ggplot2)
# Create test data.
data
```{r thecode2, eval=FALSE}
```
```{r, echo=FALSE}
htmltools::includeHTML("htmlChunkRelatedPartOfWhole.html")
```