基于 ggplot 2 中因子的颜色和大小的散点图

scatterplot with points based on color and size of factor in ggplot 2

我是 ggplot2 的新手,所以请多多包涵。我想在 ggplot2 中绘制一个散点图,我可以在其中为数据着色或根据第二个变量因子更改点的大小。我可以使用 plot() 函数对颜色执行此操作:

#simulate data
x1 <- rnorm(100)
y <- as.factor(runif(100)<=.70)
df <- data.frame(x1,y)
#plot
plot(df$x1, col = df$y,cex = 1, pch = 19)

这是我对 ggplot2 的尝试:

qplot(seq_along(df$x1), df$x1) + scale_colour_manual(breaks = df$y)

您可以通过在colshape中指定颜色和形状在aes中实现预期的输出。

library(ggplot2)
ggplot(df, aes(x=x1, y=seq(1,length(x1)),col=y, shape=y)) + geom_point()

输出:

你的问题有一个标题:基于 ggplot 2colorshape 因素的散点图

而问题中的文字说:...我可以在其中为数据着色或更改点的大小...

那么你在找什么?颜色、形状或尺寸?

您可以在 ggplot() 中使用 shapesizecolour 参数:

library(ggplot2)
ggplot(df, aes(x=seq(1,length(x1)), y=x1,colour=y, size=y)) + geom_point()

在这个例子中,我只是设置大小(size=...)和颜色(color=...)应该取决于y变量,但是你可以随意改变它。对于形状参数,只需使用 shape=...

但是:不建议对离散变量使用大小。