Bubble Charts in R

In this post post, I’m going to show you how to do nice bubble charts with R. The data are available here.

#Load the data 
tab=read.csv2("Bubble.csv")

#Boolean to identify the gender (1 Men, 2 Women)
gender=(tab[,4]==1)

#Colors
library(scales)                    #Function alpha to modify colour transparency

colo1="steelblue"                  #Color circle men                 
colo1bg=alpha(colo1, 0.5)          #Color background circle men

colo2="#CC6666"                    #Color circle women               
colo2bg=alpha(colo2, alpha=0.5)    #Color background circle women

bgcol="white"                      #Color background plot            
colo="black"                       #Color axis and labels            


#Plot
par(bg=bgcol)         #Color background
par(mar=c(5,6,2,2))   #Margins

plot(tab[gender,1], tab[gender,2], pch=21, lwd=2, cex=tab[gender,3]/10, col=colo1, bg=colo1bg, xlab="", ylab="", axes=FALSE, xlim=c(min(tab[,1])-2,max(tab[,1])+2), ylim=c(min(tab[,2])-10,max(tab[,2])+10))
par(new=T)
plot(tab[!gender,1], tab[!gender,2], pch=21, lwd=2, cex=tab[!gender,3]/10, col=colo2, bg=colo2bg, xlab="", ylab="", axes=FALSE, xlim=c(min(tab[,1])-2,max(tab[,1])+2), ylim=c(min(tab[,2])-10,max(tab[,2])+10))

axis(1, cex.axis=1.5, lwd=2, col=colo, col.axis=colo)
axis(2, cex.axis=1.5, las=1, lwd=2, col=colo, col.axis=colo)
mtext("Height", 1, line=3.5, cex=2, col=colo)
mtext("Weight", 2, line=4, cex=2, col=colo)

legend("bottomright", inset=c(0.02,0), legend=c("Men","Women"), x.intersp=0.2, lty=0, pch=21, cex=1.75, pt.cex=2.5, lwd=2, col=c(colo1,colo2), pt.bg=c(colo1bg,colo2bg), bty="n", text.col=colo)
legend("topleft", inset=c(0.02,0), legend=rep("",4), title="Age", title.adj=0.2, lty=0, pch=21, cex=1.75, pt.cex=c(4,3,2,1), lwd=2, col=colo, pt.bg=bgcol, bty="n", title.col=colo)

You can customize many features of your graphs and play with the different parameters of the plot, axis and mtext functions. For example, you can change the colors:

#Colors
library(scales)

colo1="#5CB528"                    #Color circle men                 
colo1bg=alpha(colo1, 0.5)          #Color background circle men

colo2="#EAAE28"                    #Color circle women               
colo2bg=alpha(colo2, alpha=0.5)    #Color background circle women

bgcol="#4B2E1C"                    #Color background plot            
colo="#FAC86E"                     #Color axis and labels            
comments powered by Disqus