Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add shadow effect ggplot2 bars (barplot)

Tags:

r

ggplot2

I'm attempting to show poorer design choices in plots. One of the ink wasting, potentially distracting effects people use if a shadow effect of bars. I'd like to make ggplot2 do this. The basic thought I had was to make a first semitransparent layer of bars slightly higher and shifted to the right. I can get the slightly higher but not the slightly to the right:

dat <- data_frame(
    School =c("Franklin", "Washington", "Jefferson", "Adams", "Madison", "Monroe"),
    sch = seq_along(School),
    count = sort(c(13, 17, 12, 14, 3, 22), TRUE),
    Percent = 100*round(count/sum(count), 2)
)

dat[["School"]] <- factor(dat[["School"]], levels = c("Franklin", 
    "Washington", "Jefferson", "Adams", "Madison", "Monroe"))

ggplot(dat) +
   geom_bar(aes(x = School, weight=Percent + .5), alpha=.1, width = .6) +
   geom_bar(aes(x = School, weight=Percent, fill = School), width = .6) +
   theme_bw()

enter image description here

This attempt gives the following warning and that transparent layer is ignored (which is sensible):

ggplot(dat) +
   geom_bar(aes(x = School + .2, weight=Percent + .5), alpha=.1, width = .6) +
   geom_bar(aes(x = School, weight=Percent, fill = School), width = .6) +
   theme_bw()

## Warning messages:
## 1: In Ops.factor(School, 0.2) : ‘+’ not meaningful for factors
## 2: In Ops.factor(School, 0.2) : ‘+’ not meaningful for factors
   
like image 250
Tyler Rinker Avatar asked Mar 11 '15 21:03

Tyler Rinker


2 Answers

I think maybe this is what you're looking for...?

ggplot(dat) +
    geom_bar(aes(x = as.integer(School) + .2, y= Percent - .5),stat = "identity", alpha=.2,width = 0.6) +
    geom_bar(aes(x = as.integer(School), y=Percent, fill = School),stat = "identity",width = 0.6) +
    scale_x_continuous(breaks = 1:6,labels = as.character(dat$School)) +
    theme_bw()

enter image description here

like image 189
joran Avatar answered Oct 20 '22 21:10

joran


Using what @joran gave me this works (Thanks Joran):

ggplot(dat) +
    geom_bar(aes(x = School, y=Percent), fill=NA, color=NA, width = .6, stat = "identity") +
    geom_bar(aes(x = sch + .075, y=Percent + .5), alpha=.3, width = .6, stat = "identity") +
    geom_bar(aes(x = School, y=Percent, fill = School), width = .6, stat = "identity")

The key is:

  1. Add another layer before the transparent layer that is identical to the color bars, but don't fill or color them (use NA)
  2. Make a numeric version of the factor (in my case I had made sch but didn't work without previous step
  3. Don't use weight but instead use y & stat = "identity"

enter image description here

like image 36
Tyler Rinker Avatar answered Oct 20 '22 22:10

Tyler Rinker