Pie chart

Macrobond R API is available for users with Data+ and Legacy license (the latter without searching and revision history functions). Examples were tested on Macrobond version 1.25, Macrobond API for R version 1.2-8 and R 4.2.0.

See two methods of constructing pie charts - with baseR and ggplot2. Examples are presented on United State's presidential approval data from FiveThirtyEight.

 

Pie chart version 1 created with baseR package (click to enlarge). Jump to code with baseR package.

 

 

 

 

Pie chart version 2 with ggplot2 package (click to enlarge). Jump to code with ggplot2 package.

With baseR package

library(MacrobondAPI)
#baseR

#get series, calculate N/A series
appr<-getValues(FetchOneTimeSeries("uspoli3001"))
disappr<-getValues(FetchOneTimeSeries("uspoli3002"))
na<-abs(100-(appr+disappr))

#create vector with last values from each series
answer<-c(last(appr), last(disappr), last(na))

#create elements for pie chart
labels<-c("Yes","No","N/A")
colors<-c("#17456d", "#CD545B", "#787276")
title<-"Approval for President Biden"

#create pie chart
pie(answer, labels = labels, border="white", col=colors, main=title, clockwise=TRUE)

With ggplot2 package

library(MacrobondAPI)
library(ggplot2)

#get series, calculate N/A series
appr<-getValues(FetchOneTimeSeries("uspoli3001"))
disappr<-getValues(FetchOneTimeSeries("uspoli3002"))
na<-abs(100-(appr+disappr))

#create data frame with values and categories
answer<-c(last(appr), last(disappr), last(na))
labels<-c("Yes","No","N/A")
df<-data.frame(answer, labels)

#create pie chart with legend and value labels
ggplot(df, aes(x = "", y = answer, fill = labels)) +
  geom_bar(stat="identity", width=1, color="white") +
  coord_polar(theta = "y") + #create circle
  scale_fill_manual(values = c("#787276","#CD545B","#17456d"))+ #set colors
  guides(fill = guide_legend(reverse=TRUE, title = "Answer")) + #reverse legend, set legend's title
  geom_label(aes(label = round(answer, 1)), color = c("white", "white", "white"),
             position = position_stack(vjust = 0.5), show.legend = FALSE) + #settings for value labels
  theme_void() #remove background images
ggtitle("Approval for President Biden")+ 
theme(plot.title=element_text(size=rel(2), hjust=0.5)) #title settings