Easy Tutorial
❮ R Input Xml File R Data Frame ❯

R Plotting - Pie Chart

R language provides a large number of libraries to implement plotting functions.

A pie chart, or pie graph, is a circular statistical graphic divided into sectors, which illustrates proportion, frequency, or percentages.

pie(x, labels = names(x), edges = 200, radius = 0.8,
    clockwise = FALSE, init.angle = if(clockwise) 90 else 0,
    density = NULL, angle = 45, col = NULL, border = NULL,
    lty = NULL, main = NULL, …)

To draw a pie chart, you need to prepare these elements: a vector reflecting quantities, labels for each part, and colors for each part (optional).

Next, we will draw a simple pie chart:

Example

# Data preparation
info = c(1, 2, 4, 8)

# Naming
names = c("Google", "tutorialpro", "Taobao", "Weibo")

# Coloring (optional)
cols = c("#ED1C24","#22B14C","#FFC90E","#3f48CC")

# Plotting
pie(info, labels=names, col=cols)

Executing the plotting program will generate a PDF file (Rplots.pdf) in the current directory. Opening the file will show the graphical effect as follows:

We can also use png(), jpeg(), bmp() functions to set the output file format as an image:

Example

# Data preparation
info = c(1, 2, 4, 8)

# Naming
names = c("Google", "tutorialpro", "Taobao", "Weibo")

# Coloring (optional)
cols = c("#ED1C24","#22B14C","#FFC90E","#3f48CC")

# Setting output image
png(file='tutorialpro-pie.png', height=300, width=300)
# Plotting
pie(info, labels=names, col=cols)

Next, we will set a title for the pie chart. Chinese fonts need to set the font parameter family='GB1', or you can set your own font library. For details, refer to: R Plotting - Chinese Support.

Example

# Data preparation
info = c(1, 2, 4, 8)

# Naming
names = c("Google", "tutorialpro", "Taobao", "Weibo")

# Coloring (optional)
cols = c("#ED1C24","#22B14C","#FFC90E","#3f48CC")
# Calculating percentages
piepercent = paste(round(100*info/sum(info)), "%")
# Plotting
pie(info, labels=piepercent, main = "Website Analysis", col=cols, family='GB1')
# Adding color sample annotation
legend("topright", names, cex=0.8, fill=cols)

To draw a 3D pie chart, you can use the pie3D() function from the plotrix library. Before using it, we need to install it:

install.packages("plotrix", repos = "https://mirrors.ustc.edu.cn/CRAN/")

Example

# Loading plotrix
library(plotrix)
# Data preparation
info = c(1, 2, 4, 8)

# Naming
names = c("Google", "tutorialpro", "Taobao", "Weibo")

# Coloring (optional)
cols = c("#ED1C24","#22B14C","#FFC90E","#3f48CC")

# Setting file name, output as png
png(file = "3d_pie_chart.png")

# Plotting 3D chart, family should be set to a Chinese font library supported by your system
pie3D(info,labels = names,explode = 0.1, main = "3D Chart",family = "STHeitiTC-Light")

The generated image is as follows:

❮ R Input Xml File R Data Frame ❯