Tutorial for Pie Chart in ggplot2 with Examples

Tutorial for Pie Chart in ggplot2 with Examples

Dataset

We are going to create our own toy sample dataset of mobile phone companies and their market share. This is loaded into a data frame ‘data’ that will be used throughout the ggplot2 pie chart examples.

 

Out[3]:

Example 4: Applying Gray Scale to Pie Chart using scale_fill_grey()

If we want to opt for a grey color palette for coloring pies of the pie chart in ggplot2, then we can use scale_fill_grey() as shown in the below example.

In [4]:

ggplot(data, aes(x="", y=percent, fill=brand)) +
geom_bar(stat="identity", width=1) +
coord_polar("y", start=0) +
geom_text(aes(label = paste0(percent, "%")), position = position_stack(vjust=0.5)) +
labs(x =NULL, y = NULL, fill = NULL) +
scale_fill_grey()

Out[4]:

pie chart in R ggplot2 Example

Out[5]:
Out[7]:
pie chart in R ggplot2 geom_label() Example
Out[8]:

The legend title can be customized with guides() layer as shown in the below example where the title has been changed to “Phone Companies”

In [9]:

ggplot(data, aes(x = "",y=percent, fill=brand)) + 
geom_col(color = "black") + 
geom_label(aes(label = paste0(percent, "%")), color = "white", position = position_stack(vjust = 0.5), size=8, show.legend = FALSE) + 
coord_polar(theta = "y") +
guides(fill = guide_legend(title = "Phone Companies"))

 

Out[9]:

pie chart in ggplot2 custom legend title Example

The legend can be placed at several places, possible placement values are “bottom”, “left”, “top” and “right” (default). To place the legend at the bottom use the legend.position = “bottom” in the theme layer.

Out[10]:
Out[11]:

LEAVE A REPLY

Please enter your comment!
Please enter your name here