3


I'd like to create a ggplot which use two variables to fill in different way. Based on this solution I made

x = c("Band 1", "Band 2", "Band 3")
y1 = c("1","2","3")
y2 = c("2","3","4")

to_plot <- data.frame(x=x,y1=y1,y2=y2)
melted<-melt(to_plot, id="x")

ggplot(melted,aes(x=x,y=value,fill=variable)) + 
        geom_bar(stat="identity",position = "identity", alpha=.3)

enter image description here

but instead of alpha parameter, I'd like to color each Band value in different way and implement y1 as white bar with border in color of a given Band and y2 as bar with color of of a given Band. How to do it?

Community
  • 1
  • 1
Nicolabo
  • 1,337
  • 12
  • 30

1 Answers1

5

Here's my best attempt. You'll need several overrides here and there since your plot is not "ggplot-canonical" w.r.t. to aes mapping.

# extra variable to map to fill
melted$col <- ifelse(melted$variable == "y1", "white", melted$x)
# reorder appearance, so that y1 is plotted after y2
melted <- with(melted, melted[order(-as.numeric(variable)), ])

ggplot(melted, aes(x=x, y=value, fill=col, color=x, alpha=variable)) + 
  geom_bar(stat="identity", position="identity", size=2) + 
  scale_fill_manual(values = c("red", "green", "blue", "white"), guide=FALSE) + 
  scale_color_manual(values = c("red", "green", "blue")) + 
  scale_alpha_manual(values = c(1, 0.5), guide=FALSE)

enter image description here

tonytonov
  • 25,060
  • 16
  • 82
  • 98
  • 1
    cumbersome but I guess this is the expected result! – Colonel Beauvel Apr 03 '15 at 10:31
  • @tonytonov One more thing. When you add `scale_alpha_manual(values = c(1, 0.5))` without `guide = F` you get black rectangle and gray rectangle in legend. How to change gray color to white? – Nicolabo Apr 03 '15 at 11:11
  • 1
    @Nicolabo http://stackoverflow.com/questions/16356052/control-ggplot2-legend-look-without-affecting-the-plot – tonytonov Apr 03 '15 at 11:36