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:
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.
You can use function guides() and then with argument override. aes= set line size= (width) to some large value. To remove the grey area around the legend keys set fill=NA for legend. key= inside theme() .
You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))
To change the Size of Legend, we have to add guides() and guide_legend() functions to the geom_point() function. Inside guides() function, we take parameter color, which calls guide_legend() guide function as value. Inside guide_legend() function, we take an argument called override.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With