使用连续变量将 fill/colour 更改为 geom_dotplot 或 geom_histogram

Change fill/colour for geom_dotplot or geom_histogram with a continuous variable

是否可以用连续变量填充 ggplot 的 geom_dotplot?

library(ggplot2)
ggplot(mtcars, aes(x = mpg, fill = disp)) +
  geom_dotplot()

这应该是非常简单的,但我已经尝试弄乱组 aes 但没有成功。

我最多只能离散化 disp 变量,但这不是最优的。

ggplot(mtcars, aes(x = mpg, fill = factor(disp))) +
  geom_dotplot()

好问题!您必须在 aes 内设置 group = variable(其中 variable 等于您用于 fillcolor 的同一列):

library(ggplot2)
ggplot(mtcars, aes(mpg, fill = disp, group = disp)) +
  geom_dotplot()

geom_dotplot in away 就像一个直方图。分组完成后,您无法在那里轻松设置 fill/colour 。要使其工作,您必须设置 group.

示例使用 geom_histogram:

ggplot(mtcars, aes(mpg, fill = disp, group = disp)) +
  geom_histogram()