ggplot:更改图例中显示的点大小美学值

ggplot: change values shown in legend for point size aesthetic

当我在 ggplot 中使用尺寸美学和 geom_point() 时,我经常想扩大默认图例中显示的值的范围。例如,在此图中,有几个点的值 hp 比图例中显示的最小值 (100) 小得多,reader 可能难以猜测该值是什么可能是:

library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg, size = hp)) + 
  geom_point()

reprex package (v2.0.1)

于 2022-02-25 创建

如何更改图例以显示与我选择的值相对应的大小,例如c(50, 150, 250)?

您可以使用scale_size_continuous

library(ggplot2)

ggplot(mtcars, aes(x = wt, y = mpg, size = hp)) + 
  geom_point() +
  scale_size_continuous(range  = c(0.1, 10), 
                        limits = c(0, 500), 
                        breaks = c(0, 50, 100, 200, 400)

如果你想强调范围内的差异(同时失去area-proportionality使这样的情节更多'honest'),你也可以使用转换:

sq <- scales::trans_new("squared", function(x) x^2, sqrt)

ggplot(mtcars, aes(x = wt, y = mpg, size = hp)) + 
  geom_point(shape = 21, fill = "deepskyblue3") +
  scale_size_continuous(range  = c(0.1, 10), 
                        limits = c(0, 350), 
                        breaks = c(0, 50, 100, 150, 200, 250, 300, 350),
                        trans  = sq) +
  theme_bw()