Reputation: 161
Im trying to confine the fill of b & c to their respective shapes. The fill not being tied to a variable for the geom_bar is confusing but needs to be preserved for the final plot to work.
ggplot2 version is 3.3.6
library(tidyverse)
plot_data <- tibble(
percentage_a = 40,
percentage_b = 60,
percentage_c = 80,
label_b = "percentage b",
label_c = "percentage c"
)
color_palette <- c(
"#bdd7ee", # a
"#4f81bd", # b
"#254061" # c
)
ggplot(data = plot_data, aes(x = "1")) +
geom_bar(aes(y = percentage_a, fill = "percentage a"), stat = "identity", width = 1.15) +
geom_point(aes(y = percentage_b, fill = label_b), shape = 23, size = 10, position = position_nudge(x = -0.3)) +
geom_point(aes(y = percentage_c, fill = label_c), shape = 21, size = 10, position = position_nudge(x = 0.3)) +
guides(fill = guide_legend(size = 0.2,
title = "",
override.aes = list(shape = c(NA, 23, 21)
)
)) +
scale_y_continuous(limits = c(-0.5, 100), expand = c(0.001, 0), labels = scales::percent_format(scale = 1)) +
scale_fill_manual(values = color_palette)
Here is a photoshoped picture of what the plot, specifically the legend, should look like:
Edit: The chosen answer works with ggplot 3.5.1 and above.
Upvotes: 0
Views: 67
Reputation: 3854
Setting fill = 'white'
(or NA
) for the legend.key
element will remove the grey background from the shapes.
library(tidyverse)
ggplot(data = plot_data, aes(x = "1")) +
geom_bar(aes(y = percentage_a, fill = "percentage a"), stat = "identity", width = 1.15) +
geom_point(aes(y = percentage_b, fill = label_b), shape = 23, size = 10, position = position_nudge(x = -0.3)) +
geom_point(aes(y = percentage_c, fill = label_c), shape = 21, size = 10, position = position_nudge(x = 0.3)) +
guides(fill = guide_legend(size = 0.2,
title = "",
override.aes = list(shape = c(NA, 23, 21)
)
)) +
scale_y_continuous(limits = c(-0.5, 100), expand = c(0.001, 0), labels = scales::percent_format(scale = 1)) +
scale_fill_manual(values = color_palette) +
theme(legend.key = element_rect(fill = "white"))
Upvotes: 1