I have discovered an unexpected behavior while playing with changing layers in a ggplot object. I start with an initial plot.
library(ggplot2)
p <-
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Petal.Width, size = Petal.Length)) +
geom_point() +
scale_x_continuous(position = 'top') +
scale_size_area('Size Name', max_size = 12) +
scale_color_gradientn(
'Color Name',
colors = scales::brewer_pal(type = 'div')(7),
limits = c(-3, 3),
breaks = c(-3, -1.5, 0 , 1.5, 3)
)
print(p)
I then decide that I want to change the points layer to a points layer with a different shape, 21. Shape 21 has fill instead of color. However, I want to keep everything else the same. To save typing, I first remove the initial points layer, and then add the new one in. However, I find that the legend for fill does not display when it should.
p$layers
#> [[1]]
#> geom_point: na.rm = FALSE
#> stat_identity: na.rm = FALSE
#> position_identity
p$layers[[1]] <- NULL
p_with_name <-
p +
geom_point(aes(fill = Petal.Width), shape = 21, color = 'black') +
scale_fill_gradientn(
'Color Name',
colors = scales::brewer_pal(type = 'div')(7),
limits = c(-3, 3),
breaks = c(-3, -1.5, 0 , 1.5, 3)
)
print(p_with_name)
However, when I add the fill scale without a title, or with a different title from the color scale, it display properly.
p_no_name <-
p +
geom_point(aes(fill = Petal.Width), shape = 21, color = 'black') +
scale_fill_gradientn(
colors = scales::brewer_pal(type = 'div')(7),
limits = c(-3, 3),
breaks = c(-3, -1.5, 0 , 1.5, 3)
)
print(p_no_name)
p_diff_name <-
p +
geom_point(aes(fill = Petal.Width), shape = 21, color = 'black') +
scale_fill_gradientn(
'Diff Name',
colors = scales::brewer_pal(type = 'div')(7),
limits = c(-3, 3),
breaks = c(-3, -1.5, 0 , 1.5, 3)
)
print(p_diff_name)
Created on 2020-05-28 by the reprex package (v0.3.0)
Is it possible to add a fill scale with the same name as the color scale and have it appear? It would help me to simplify my code a lot.




