Open In App

Donut Chart in R

Last Updated : 01 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Donut charts are a type of circular chart like pie charts but with hole in the middle. They’re great way for showing data in aeasy-to-see way. If you’re using R, there are loads of packages to make donut charts – think ggplot2, plotly, webr, and others. 

 Donut charts are used to show data in a circular manner . Since all of the data points are centered on the donut’s rim, it is simple to compare various data points. Additionally, since the size of the slice corresponds to the amount of the data. donut charts can be used to evaluate proportions. Donut charts are a flexible and effective method to show data in general way . 

Concepts:

If we want to make a donut chart using R Programming, there are three main things we need to know. Firstly, we need the data we want to show on the chart, saved in a way that makes plotting easy like a vector or a data frame. Next, we have to select a package to make the chart with – each package’s got their own way of making and personalizing charts. And lastly, we need to figure out the various parts of the chart like the colors, labels, and slices, and how to tweak them to provide the full story we want to tell.

Steps:

Below is the basic steps outlined to create donut chart in R:

  1. Load the package that we want to use to create the chart. For example, we can use the following command to load the ggplot2 package: library(ggplot2)
  2. Prepare the data that we want to display in the chart, it should be in a format that can be easily plotted, such as a data frame or a vector.
  3. Now, use the appropriate function from the package to create the chart. For example, we can use the ggplot function from the ggplot2 package to create a basic donut chart.
  4. Customize the chart by adjusting the slices, labels, colors, and other elements as needed. Each package has its own set of functions and syntax for customizing the chart.

Example 1: Simple pie and a donut graph together on one plot using ggplot2

The first thing we do is to create a sample dataset that includes the categories and values that we want to plot:

R




library(ggplot2)
library(gridExtra)
data <- data.frame(
  Category = c("A", "B", "C", "D"),
  Value = c(20, 30, 40, 10)
)


Then next we create pie chart by mapping Value variable to the y aesthetic and Category variable to fill aesthetic:

R




pie_chart <- ggplot(data, aes(x = "", y = Value, fill = Category)) +
  geom_bar(stat = "identity", width = 1) +
  coord_polar(theta = "y") +
  geom_text(aes(label = paste(Category, round(Value/sum(Value) * 100), "%")),
            position = position_stack(vjust = 0.5)) +
  scale_fill_brewer(palette = "Dark2") +
  theme_void()


The size of each bar in bar graph formed by geom_bar command with stat = “identity” is determined by Value factor. The coord_polar transformation transforms bar chart into pie chart by changing coordinate system to polar coordinates. To provide the category and percentage of the whole that the value stands for, the geom_text function adds labels to the chart. The scale_fill_brewer function sets the fill colors to a brewer library color palette.

By setting fill = “white” and a lower width, we use the geom_bar command yet again to create the donut chart, which has a white core.

R




donut_chart <- pie_chart +
  geom_bar(data = data, aes(x = "", y = Value), stat = "identity",
           width = 0.5, fill = "white") +
  geom_text(data = data, aes(label = paste(Category, round(Value/sum(Value) * 100), "%")),
            position = position_stack(vjust = 0.5), color = "black") +
  theme_void()


Note that we’ve added data parameter to geom_bar and geom_text functions so that we can reuse same dataset for donut chart. The width parameter of 0.5 creates a smaller circle in middle of chart and fill = “white” sets fill color of circle to white. The color = “black” parameter of geom_text sets color of the labels to black.

Finally, we use the grid.arrange function from gridExtra package to arrange pie and donut charts side by side on same plot:grid.arrange(pie_chart, donut_chart, ncol = 2, widths = c(3, 3))

R




grid.arrange(pie_chart, donut_chart, ncol = 2, widths = c(3, 3))


The ncol = 2 parameter will make it so there’s only 2 columns in the picture, and widths = c(3, 3) will make both of those columns 3 inches wide.

Output

Donut Chart in R

 

Customizing the Donut chart

You can customize the pie donut chat, because there are many prominent customizations that can be done to the donut chart Like:

  • We could customize the chart by changing the width of the donut:

R




donut_chart <- pie_chart +
  geom_bar(data = data, aes(x = "", y = Value), stat = "identity",
           width = 0.3, fill = "white") +
  geom_text(data = data, aes(label = paste(Category, round(Value/sum(Value) * 100), "%")),
            position = position_stack(vjust = 0.5), color = "white") + # changed color to white
  theme_void()
 
grid.arrange(pie_chart, donut_chart, ncol = 2, widths = c(3, 3))


  • Using this code, a polar bar chart with a vacant x-axis can be produced.
  • With data as the information and aes() as the aesthetics mapping, geom_bar() generates a bar chart. The y aesthetic is mapped to the Value column of the dataset, and the x aesthetic is kept empty to produce a polar chart. stat = “identity” plots the real values.
    width = 0.3 specifies a 0.3 breadth for the bars.
  • The color of the segments is changed to white by fill = “white.”
  • Using the y line as the angle, coord_polar(theta = “y”) transforms the polar coordinates from the Cartesian system.
     
     

R




pie_chart <- ggplot(data, aes(x = "", y = Value, fill = Category)) +
  geom_bar(stat = "identity", width = 1) +
  coord_polar(theta = "y") +
  geom_text(aes(label = paste(Category, round(Value/sum(Value) * 100), "%")),
            position = position_stack(vjust = 0.5), color = "black") +
  scale_fill_brewer(palette = "Set2") +
  theme_void()
 
donut_chart <- pie_chart +
  geom_bar(data = data, aes(x = "", y = Value), stat = "identity",
           width = 0.3, fill = "white") +
  geom_text(data = data, aes(label = paste(Category, round(Value/sum(Value) * 100), "%")),
            position = position_stack(vjust = 0.5), color = "black") +
  theme_void()
 
grid.arrange(pie_chart, donut_chart, ncol = 2, widths = c(3, 3))


  • Setting the color scheme for the fill aesthetic in a ggplot2 plot requires the use of the scale_fill_brewer() method. Which colour scheme to use is specified by the palette parameter. In this instance, the “Set2” palette from the ColorBrewer2.org library, a set of color schemes created for use in data visualization, is being used.
  • The eight colors in the “Set2” palette are created to be readily distinguishable from one another. It is frequently employed when several categories or groups need to be depicted in a single plot.
  • We can also jazz up the text on the chart by playing around with the theme() function and the element_text() function. 
  • Text can be added to a ggplot2 plot using the geom_text() method. In this instance, labels are being added to a layered bar chart. 
  • The dataset’s Category column and the percentage determined from the Value column are concatenated to produce the label parameter using the paste() function. The percentage is rounded to the nearest whole figure using the round() function. The Value column’s total value, which is used to compute the percentage, is calculated using the sum() function.
  • And if we want, we can throw in a chart title using the labs() function to add a title to the chart.
  • To make the chart bigger or smaller, we can tinker with the theme() function. To increase the size, we can change with the plot.margin parameter. To tweak the title, we can adjust the plot.title parameter. And if we want to customize the legend, we can use the legend.position parameter. Here’s how it’s done:

Output

Donut Chart in R

 

These are just a few of the many functions and parameters that can be used to customize the donut chart. There are many other options available in the ggplot2 package.

Example 2: Pie-Donut Chart for Sample Browser Market Share using webr.

First, we load the necessary libraries webr.

The webr package is an R Programming package that provides functions to extract data from web pages using web scraping techniques.

R




# Load webr
library(webr)


We create a new dataset named devices. It has three columns, device which is a factor variable that takes on the values of Desktop, Mobile, and Tablet, browser which is also a factor variable that takes on the values of Chrome and Safari and share which represents the percentage of market share for a given device and browser combination.

R




# Create a new dataset
devices <- structure(
  list(
    device = structure(
      c(1L, 1L, 2L, 2L, 3L, 3L),
      .Label = c("Desktop", "Mobile", "Tablet"),
      class = "factor"
    ),
    browser = structure(
      c(1L, 2L, 1L, 2L, 1L, 2L),
      .Label = c("Chrome", "Safari"),
      class = "factor"
    ),
    share = c(60, 40, 80, 20, 50, 50)
  ),
  .Names = c("device", "browser", "share"),
  row.names = c(NA, -6L),
  class = "data.frame"
)


We use the PieDonut function from the webr library to create a Pie-Donut chart. We provide the devices dataset as the first argument and specify the aes aesthetic mapping. We map the device variable to the x aesthetic and the browser variable to the y aesthetic. We also set ratioByGroup to FALSE to create a traditional Pie-Donut chart.

R




# Create a Pie-Donut chart using webr library
PieDonut(devices, aes(x = device, y = browser, count = share),
         ratioByGroup = FALSE)


Output:

 

The resulting Pie-Donut chart shows the market share distribution for each device and browser combination, with the size of the sectors indicating the percentage of market share. The outer ring represents the device variable, with Desktop, Mobile, and Tablet shown in clockwise order.

Customizing the chart

Explode Pie and Donuts.

A pie and donut combo chart is made using the PieDonut() function. The aes() function is used to translate the device and browser columns to the chart’s x- and y-axes, respectively. The extent of each slice of the chart is set using the count parameter.

The degree of separation between the pie chart’s slices is determined by the explode parameter, which is set to 2, which is. Each segment is now isolated from the others in a “exploded” effect. When the explodeDonut parameter is set to TRUE.which separates the segments in the donut chart .

R




PieDonut(devices, aes(x = device, y = browser, count = share),
         explode = 2, explodeDonut = TRUE,
         ratioByGroup = FALSE)


 

Explode Pie and Donuts independently.

To explode specific slices in both the Pie and Donut charts independently, the “selected” argument is used. The values passed to “selected” are the indices of the slices to be exploded.

R




PieDonut(devices, aes(x = device, y = browser, count = share),
         explode = 2, explodeDonut = TRUE,
         selected = c(2,4,6),
         ratioByGroup = FALSE)


 

Customize start angle.

To change the starting angle of the chart, the “start” argument is used. The angle is specified in degrees.

R




PieDonut(devices, aes(x = device, y = browser, count = share),
         explode = 2, explodeDonut = TRUE,
         selected = c(2,4,6),
         start = 120,
         ratioByGroup = FALSE)


 

Add title.

To add a title to the chart, the “title” argument is used. The title is passed as a string.

R




PieDonut(devices, aes(x = device, y = browser, count = share),
         explode = 2, explodeDonut = TRUE,
         selected = c(2,4,6),
         start = 120,
         title = "Browser market share by device",
         ratioByGroup = FALSE)


 

Adjust the radius.

To adjust the radius of the chart, we can use the r0, r1, and r2 arguments of the PieDonut function.

  • r0 controls the inner radius of the chart. The default value is 0.4, which means the inner radius is 40% of the total radius.
  • r1 controls the outer radius of the chart. The default value is 0.8, which means the outer radius is 80% of the total radius.
  • r2 controls the radius of the donut hole. The default value is 0, which means there is no donut hole.
    To adjust the radius of the chart, we can change the values of r0, r1, and r2.

To adjust the radius of the chart, we can change the values of r0, r1, and r2. 

R




PieDonut(devices, aes(x = device, y = browser, count = share),
         explode = 2, explodeDonut = TRUE,
         selected = c(2,4,6),
         start = 120,
         title = "Browser market share by device",
         r0=0.3,r1=0.6,r2=0.9,
         ratioByGroup = FALSE)


 

Doughnut plot

To show donut plot without the pie chart:

R




PieDonut(devices, aes(browser, count = share),
         r0=0.6)


The devices data frame is used as the input data, and the aes function is used to map the browser variable to the x axis and the share variable to the y axis. The count argument specifies that the share variable should be used to calculate the size of each slice in the plot.

 

Example 3: Donut Chart using plotly package

The plotly package is an R Programming package that provides an interface to create interactive web-based visualization using the Plotly JawaScript library.

R




library(plotly)
 
# create a data frame with category labels and corresponding values
data <- data.frame(
  category = c("A", "B", "C", "D", "E"),
  value = c(20, 25, 15, 10, 30)
)
 
# define the colors for each category
colors <- c("red", "orange", "yellow", "green", "blue")
 
# set the marker properties, including the colors and line width
marker <- list(colors = colors)
 
# create the pie chart with a hole in the center
plot_ly(data, labels = ~category, values = ~value, type = "pie",
        hole = 0.5, marker = marker)


First, a data frame is created with five categories labeled A through E, and their corresponding values. Then, a vector of colors is defined for each category.

Next, the marker variable is defined to include the colors for each category and any other marker properties such as line width.

Finally, the plot_ly function is used to create the pie chart, with the data data frame as the input, the category column as the labels, the value column as the values, and type = “pie” to specify that it is a pie chart. The hole parameter specifies the size of the hole in the center of the chart, and marker = marker applies the marker properties defined earlier.

 

Customizing the chart

Add title to the chart.

R




plot_ly(data, labels = ~category, values = ~value, type = "pie",
        hole = 0.5, marker = marker)%>%
   
  # customize the layout of the chart, including the title and legend
  layout(title = "Donut Chart Example")


 

The layout function is used to add a title to the chart, with the text “Donut Chart Example”. This improves the chart by adding context and clarity to what the chart is showing.

 

Add a label and text info

R




# define the text and hover information to be displayed on the chart
textinfo <- "label+percent"
hoverinfo <- "text"
...
# create the pie chart with a hole in the center
plot_ly(data, labels = ~category, values = ~value, type = "pie",
        hole = 0.5, marker = marker,
        text = ~paste(category, value, sep = ": "),
        textinfo = textinfo, hoverinfo = hoverinfo)


  ...

To improve the chart by providing more information and context for the data presented and making it easier for the viewer to interpret and understand the chart. The text parameter is added to display the label and value of each category on the chart, separated by a colon (:). The textinfo parameter is also defined as “label+percent” to show both the label and the percentage of each category in the chart.

Additionally, the hoverinfo parameter is set to “text” to display the text defined in text when the user hovers over each category in the chart.

 

Donut chart thickness

R




plot_ly(data, labels = ~category, values = ~value, type = "pie",
        hole = 0.8, marker = marker)%>%
   
  # customize the layout of the chart, including the title and legend
  layout(title = "Donut Chart Example")


We can maintain the thickness of donut chart by increase or decrease the value in hole.

 

Adding Custom color Palettes 

R




# define the colors for each category
colors <- c("#2ecc71", "#3498db", "#f1c40f", "#e74c3c", "#9b59b6")
 
# set the marker properties, including the colors and line width
marker <- list(colors = colors)


The colors of the pie chart are changed to a custom color palette. Specifically, the hex codes for five colors (green, blue, yellow, red, and purple) are defined and stored in the colors vector. These colors are then passed to the marker parameter to set the colors for each category in the pie chart.

This change improves the chart by using a custom color scheme that is more visually appealing and/or aligned with a particular branding or design style.

 

Customizing legend

R




colors <- c("#2ecc71", "#3498db", "#f1c40f", "#e74c3c", "#9b59b6")
 
# set the marker properties, including the colors and line width
marker <- list(colors = colors)
 
# define the text and hover information to be displayed on the chart
textinfo <- "label+percent"
hoverinfo <- "text"
 
# create the pie chart with a hole in the center
chart <- plot_ly(data, labels = ~category, values = ~value, type = "pie",
                 hole = 0.5, marker = marker,
                 text = ~paste(category, value, sep = ": "),
                 textinfo = textinfo, hoverinfo = hoverinfo)
 
# customize the layout of the chart, including the title and legend
layout(chart, title = "Donut Chart Example",
       legend = list(x = 0, y = 1, font = list(size = 14, color = "black")))


Added a legend customization to the plot using the layout function. The purpose of this change is to adjust the position and font of the legend to make it more readable and aesthetically pleasing. 

 

Adding a Pie Slice Border

R




chart <- plot_ly(data, labels = ~category, values = ~value, type = "pie",
                 hole = 0.5, marker = marker,
                 text = ~paste(category, value, sep = ": "),
                 textinfo = textinfo, hoverinfo = hoverinfo)
 
# customize the layout of the chart, including the title and legend
layout(chart, title = "Donut Chart Example",
       legend = list(x = 0, y = 1, font = list(width = 2, color = "blue")))


Added the “line” parameter to the “marker” list with values specifying the color and width of the marker line. This adds a line border around each pie slice. 

 

Conclusion:

Donut charts are a great way of presenting data in a circular format with a hole in the center, and there are tons of R packages out there that can help you make them. In this article, we dug into how to get creative with donut charts using ggplot2 and other packages, and how to make your data look sharp and stylish. We figured out that you can create donut charts by turning bar charts into polar coordinate systems, and using this nifty coord_polar function. Plus, we also explored around with customizing the chart by changing the slice width, tweaking colors and labels, and even blending pie and donut charts together. So, armed with the know-how to create and spruce up your own donut charts in R, data whizzes everywhere can create effective visualizations for their data presentations.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads