Nils Mackay Nils Mackay - 26 days ago 7
R Question

R - Change the shape of legend key for geom_bar in ggplot2

I'm trying to change the shape of the legend key from a geom_bar graph. I've looked at multiple answers online but found they didn't work in this case. Let me explain the problem:

df1 = data.frame(person = c("person1", "person2", "person3"),
variable = "variable1",
value = c(0.5, 0.3, 0.2))

df2 = data.frame(person = c("person1", "person2", "person3"),
variable = "variable2",
value = c(-0.3, -0.1, -0.4))


I'm trying to make a stacked barplot where one side is negative. Using ggplot2 I get:

library(ggplot2)
ggplot() + geom_bar(data = df1, aes(x = person, y = value, fill = variable), stat = "identity") +
geom_bar(data = df2, aes(x = person, y = value, fill = variable), stat = "identity") +
scale_fill_manual(values = c("steelblue", "tomato"), breaks = c("variable1","variable2"),
labels = c("Variable 1", "Variable 2"))


It then looks like this:

enter image description here

Now on the right the legend shows squares by default. Is there a way to change this into a circle for instance?

Online I've found the way this usually works is by using

guides(fill = guide_legend(override.aes = list(shape = 1)))


Or similar variations. However this doesn't seem to work. If anybody can help that would be great, I've been stuck for quite a while now.

dww dww
Answer

You could add a layer of geom_point with no data (just to create a legend) and hide the unwanted rectangular legend from the bars using show.legend = FALSE:

df3 = data.frame(person = as.numeric(c(NA, NA)),
                 variable = c("variable1", "variable2"),
                 value = as.numeric(c(NA, NA)))

ggplot() + 
  geom_bar(data = df1, aes(x = person, y = value, fill = variable), stat = "identity", show.legend = FALSE) +
  geom_bar(data = df2, aes(x = person, y = value, fill = variable), stat = "identity", show.legend = FALSE) +
  geom_point(data = df3, aes(x = person, y = value, color = variable), size=8) +
  scale_fill_manual(values = c("steelblue", "tomato"), breaks = c("variable1","variable2")) +
  scale_color_manual(values = c("steelblue", "tomato")) +
  theme(legend.key = element_blank())

enter image description here

Comments