Skip to content

Instantly share code, notes, and snippets.

@nassimhaddad
Last active December 13, 2015 23:49
Show Gist options
  • Save nassimhaddad/4994317 to your computer and use it in GitHub Desktop.
Save nassimhaddad/4994317 to your computer and use it in GitHub Desktop.
pie chart in ggplot2

Here I'll drop ggplot2 tricks ...

Table of Contents:

  • piechart.R: getting the order of the colors right is quite a task
  • themes.R: ggthemes is really useful
# percentage formatting
scale_x_continuous(labels = percent_format())
# Remove legend for a particular aesthetic (fill)
bp + guides(fill=FALSE)
# It can also be done when specifying the scale
bp + scale_fill_discrete(guide=FALSE)
# This removes all legends
bp + theme(legend.position="none")
library(ggplot2)
library(ggthemes)
nb_by_activity <- structure(list(Interactions = c(1337266L, 98415L, 71079L, 537486L,
56709L), InteractionDays = c(51362L, 26480L, 26061L, 24686L,
18948L), activity_name = structure(c(1L, 3L, 4L, 2L, 5L), .Label = c("task 1",
"task 4", "task 2", "task 3", "task 5"), class = "factor")), .Names = c("Interactions",
"InteractionDays", "activity_name"), row.names = c(NA, 5L), class = "data.frame")
#' to watch for:
#' to get the order of the legend right and chart right, we need multiple actions:
#' 1. correct factor order
#' 2. setting the order in aes()
#' 3. setting reverse order in coord_polar
nb_by_activity$activity_name <- factor(nb_by_activity$activity_name,
levels = nb_by_activity$activity_name[order(nb_by_activity$Interactions, decreasing=TRUE)])
activity_pie_chart <-
ggplot(nb_by_activity, aes(x = factor(1), fill = factor(activity_name), y = (Interactions)/sum(Interactions),
order = (Interactions)/sum(Interactions))) +
geom_bar(stat = "identity", width = 1) +
labs(title = sprintf("Number of Interactions by activity"), x = "", y= "") +
getstyle(15) + scale_fill_tableau("colorblind10")+
coord_polar(theta="y", direction = -1) +
theme(legend.position="right") +
theme(axis.text.y = element_blank(), axis.text.x = element_blank(),
legend.text=element_text(size=14), legend.title=element_text(size=14) )+
guides(fill = guide_legend(title = "Activity"))
plot(activity_pie_chart)
#' check also: https://github.com/jrnold/ggthemes
#' (especially for the color schemes)
#' define style for the charts ####
#' usage: g <- g +getstyle (20)
getstyle <- function(text_size = 20){
theme_bw() +
theme(axis.title.x = element_text(colour="black", size=text_size)) +
theme(axis.text.x = element_text(size = text_size)) +
theme(axis.title.y = element_text(colour="black", size=text_size)) +
theme(axis.text.y = element_text(size = text_size)) +
theme(legend.position="none") +
theme(plot.title = element_text(face="bold", size = text_size+2, vjust = 2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment