How to do a pie chart in R / RStudio with highcharter?

By | August 20, 2017

Introduction

I will show you in this tutorial how to do a pie chart in R with the library highcharter. Highcharter is a R wrapper for Highcharts javascript charting libray and its modules. The result is a html pie chart with mouse over effect.

I will use as data the election results from the German Bundestag in 2013. You can find these and other election results under http://www.electionresources.org/de/

Data Preparation

First of all, I download the data.  I will add column names for convenience reasons. For this tutorial, I am interested only in the data for Germany overall and I will remove the general statistics. Furthermore, I will remove “Christian Democratic Union/Christian Social Union” because it just aggregates the results of CDU and CSU (these two parties operate on national level as one union).

# Download data
dataset <- read.csv("http://www.electionresources.org/de/data/2013.csv", header = FALSE)
# Add the column names
colnames(dataset) <- c("Region", 
                  "Election", 
                  "Party",
                  "Votes_First_Vote",
                  "Percent_First_Vote",
                  "Direct_Seats",
                  "Votes_Second_Vote",
                  "Percent_Second_Vote",
                  "List_Seats",
                  "Total_Seats")
# Keep only results for Germany overall and remove general statistics
dataset <- subset(dataset, Region == "DE" & !(Party %in% c("Registered Electors", "Voters", "Blank or Invalid Ballots", "Valid Votes")))
# Remove "Christian Democratic Union/Christian Social Union" because it just aggregates CDU and CSU
dataset <- subset(dataset, Party != "Christian Democratic Union/Christian Social Union")
# Remove unnecessary levels
dataset$Party <- factor(dataset$Party)

For convenience reasons, I rename the remaining parties to their acronyms. This looks much better in the pie chart. 😉

# Rename parties
require(plyr)
dataset$Party <- mapvalues(dataset$Party, 
                            from = c("Christian Democratic Union (CDU)", 
                                        "Christian Social Union (CSU)", 
                                        "Social Democratic Party of Germany (SPD)", 
                                        "The Left. (DIE LINKE)", 
                                        "Alliance 90/The Greens (GR&Uuml;NE)", 
                                        "Free Democratic Party (F.D.P.)", 
                                        "Alternative for Germany (AfD)", 
                                        "Pirate Party of Germany (PIRATEN)", 
                                        "National Democratic Party of Germany (NPD)", 
                                        "Free Voters (FREIE W&Auml;HLER)", 
                                        "Others"), 
                            to = c("CDU", 
                                   "CSU", 
                                   "SPD", 
                                   "DIE LINKE", 
                                   "GRÜNE", 
                                   "FDP", 
                                   "AfD", 
                                   "PIRATEN", 
                                   "NPD",
                                   "FREIE WÄHLER",
                                   "Others"))

Create a simple pie chart

Now, I can finally start to create my first pie chart. Therefore, I use simply the prepared data and let highcharter draw me a pie chart with default settings.

# Create simple pie chart with correct colors
require(highcharter)
highchart() %>% 
 hc_chart(type = "pie") %>% 
 hc_add_series_labels_values(labels = dataset$Party, values = dataset$Votes_First_Vote, color = colors)

The chart below is the result. It has alreaydy an mouse over effect with the number of votes in the specific segment. Thus, I can directly dig deeper into the data of the different segments.

In Germany (and probably in many other countries too), the parties are usually connected with a specific color. Therefore, the chart is currently confusing because the parties are represented by other colors. Furthermore, the color of a party could change if e.g. I compare the results from different years where the countries have a different order. Therefore, my next step is to add a color based on the name of the party. I took the color codes of the different parties from Wikipedia and used for “Others” just grey.

# Define colors for the different parties
colors <- revalue(dataset$Party, c("CDU" = "#000000", "CSU" = "#0088CE", "SPD" = "#FF0000", 
 "DIE LINKE" = "#8C3473", "GRÜNE" = "#008B00", "FDP" = "#FFFF00", "AfD" = "#009EE0", 
 "PIRATEN" = "#FF820A", "NPD" = "#8B4726", "FREIE WÄHLER" = "#63B8FF", "Others" = "#808080"))

Now, I can create a simple pie chart that has the correct colors by adding this variable to the data series.

This looks already pretty nice. At least from the point of visualisation…

However, the mouse over effect gives me only the absolute number of votes. This is something where I would like to add more details. Furthermore, the chart needs a title that explains what it is about.

Adding title and detail information

In the first step, I simply format the mouse over a bit better so that it shows the absolute number of votes but also the percentage. I also add a title.

# Create pie chart with tooltips
require(highcharter)
highchart() %>% 
 hc_chart(type = "pie") %>% 
 hc_add_series_labels_values(labels = dataset$Party, values = dataset$Votes_First_Vote, color = colors)%>% 
 hc_tooltip(pointFormat = paste('{point.y} votes<br/><b>{point.percentage:.1f}%</b>')) %>%
 hc_title(text = "German Election 2013 - First Vote")

I can format the mouse over (called tooltip) with html and this allows me easily e.g. to add a line break. See the result below and try it out.

Checking my initial data set again, I figure that I have also the information about the resulting seats that the party gets in the parliament. I would like to add these information to the details, too. However, the way how I have created the pie chart above, I used only the columns with the first vote and the party names. Instead I need now to hand over the data set itself so that I can chose in the formatter the information of the seats.

As a consequence I have to rename the column that I want to use a basis for the size of the segments into “y” and the column that contains the names of the segments into “name”. Otherwise, the highcharter library would not know which column to chose.

# Create pie chart with details in the tooltip
colnames(dataset)[3] <- "name"
colnames(dataset)[4] <- "y"
highchart() %>%
 hc_chart(type = "pie") %>%
 hc_yAxis(categories = dataset$Party) %>%
 hc_add_series(data = dataset) %>%
 hc_colors(as.vector(colors)) %>%
 hc_tooltip(formatter = JS("function(){
   return (this.point.name + ':<br/>' + 
           this.y + ' votes<br/>' +
           Highcharts.numberFormat(this.percentage, 2) + '%<br />' +
           'Direct seats: ' + this.point.Direct_Seats)
           }")) %>%
 hc_title(text = "German Election 2013 - First Vote")

Now, I get a nice pie chart with the distribution of votes and where the mouse over provides more detailed information including the resulting seats in the parliament.

I hope this tutorial was helpful. Let me know if you have any questions, detect any mistakes or have any tips to simplify it even more.

4 thoughts on “How to do a pie chart in R / RStudio with highcharter?

  1. Pingback: How to do pie charts with Google Charts and Sheets – On and Off Topic

  2. Pingback: My Homepage

  3. سئو

    Hey there This blog was… how do I say it? Relevant!! Finally I’ve found something that helped me. vielen dank

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *