How to create a stack bar chart with patterns rather than colours in R

721 views Asked by At

I want to create a stacked bar chart like this code from quick R:

# Stacked Bar Plot with Colors and Legend
counts <- table(mtcars$vs, mtcars$gear)
barplot(counts, main="Car Distribution by Gears and VS",
xlab="Number of Gears", col=c("darkblue","red"),
legend = rownames(counts))

However, instead of using colours to shade the stacks, I would like to fill it with objects say circles and triangles. How do I go about it in R? Thank you.

1

There are 1 answers

1
G. Grothendieck On

There is some question regarding what you actually want but perhaps this will get you started. We will use an image of the R logo here together with a re-colored version of it flipped around a vertical line. First set up the images in pic and pic2. (These two could be replaced with any two images.) Then create the outline bars and finally fill them in. See this for more ideas: Wanted: repeated-pictogram visualization of population split

# grab image of R logo
URL <- "http://www.r-project.org/Rlogo.png"
download.file(URL, "Rlogo.png", mode = "wb")
library(png)
pic <- readPNG("Rlogo.png")

# create a pink flipped version (or read in another image)
pic2 <- pic
pic2[,, 1] <- pic2[,, 4] # make pink
pic2 <- pic2[, 200:1,] # flip 

# create outline of bars
counts <- table(mtcars$vs, mtcars$gear)
bp <- barplot(counts, col = "white")

# fill in with blue and pink reversed logos
for(i in seq_along(bp)) {
  # args are image, xleft, ybottom, xright, ytop
  rasterImage(pic, bp[i]-0.5, 0, bp[i]+0.5, counts[1,i])
  rasterImage(pic2, bp[i]-0.5, counts[1,i], bp[i]+0.5, sum(counts[,i]))
}

screenshot

Update: R logo has changed so show new logo. Also flip the logo in addition to making it pink so difference can be seen in black and white as well. Added additional comments.