I'm new to ggplot2 so please bear with me. I would like to make a scatter plot in ggplot2 where I can color the data OR change the size of the points based on a second variable factor. I am able to do this for color using the plot() function as so:
我是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)
And this is my attempt with ggplot2:
这是我对ggplot2的尝试:
qplot(seq_along(df$x1), df$x1) + scale_colour_manual(breaks = df$y)
2 个解决方案
#1
#2
0
Your question has a title: scatterplot with points based on color and shape of factor in ggplot 2
你的问题有一个标题:散点图,根据颜色和ggplot 2中的因子形状得分
whereas the text in the question says: ...where I can color the data OR change the size of the points...
而问题中的文字说:......我可以在哪里为数据着色或改变点的大小......
So what are you looking for? Colour, shape or size?
你在找什么?颜色,形状或大小?
You can use shape
,size
and colour
argument in ggplot()
:
您可以在ggplot()中使用形状,大小和颜色参数:
library(ggplot2)
ggplot(df, aes(x=seq(1,length(x1)), y=x1,colour=y, size=y)) + geom_point()
In this example i just set up that the size (size=...
) and colour (color=...
) should depend on y variable, but you can change it however you want. For the shape argument just use shape=...
在这个例子中,我只是设置尺寸(size = ...)和颜色(color = ...)应该取决于y变量,但你可以随意改变它。对于shape参数,只需使用shape = ...
However: Using size for a discrete variable is not advised.
但是:不建议使用大小作为离散变量。
#1
2
You can achieve the expected output by specifying the color and shape in col
and shape
in aes
.
您可以通过在aes中指定col和shape中的颜色和形状来实现预期输出。
library(ggplot2)
ggplot(df, aes(x=x1, y=seq(1,length(x1)),col=y, shape=y)) + geom_point()
output:
输出:
#2
0
Your question has a title: scatterplot with points based on color and shape of factor in ggplot 2
你的问题有一个标题:散点图,根据颜色和ggplot 2中的因子形状得分
whereas the text in the question says: ...where I can color the data OR change the size of the points...
而问题中的文字说:......我可以在哪里为数据着色或改变点的大小......
So what are you looking for? Colour, shape or size?
你在找什么?颜色,形状或大小?
You can use shape
,size
and colour
argument in ggplot()
:
您可以在ggplot()中使用形状,大小和颜色参数:
library(ggplot2)
ggplot(df, aes(x=seq(1,length(x1)), y=x1,colour=y, size=y)) + geom_point()
In this example i just set up that the size (size=...
) and colour (color=...
) should depend on y variable, but you can change it however you want. For the shape argument just use shape=...
在这个例子中,我只是设置尺寸(size = ...)和颜色(color = ...)应该取决于y变量,但你可以随意改变它。对于shape参数,只需使用shape = ...
However: Using size for a discrete variable is not advised.
但是:不建议使用大小作为离散变量。