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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

cumbersome but I guess this is the expected result!
@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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.