0
votes

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:

#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:

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

2 Answers

4
votes

You can achieve the expected output by specifying the color and shape in col and shape in aes.

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

output:

enter image description here

0
votes

Your question has a title: scatterplot with points based on color and shape of factor in 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():

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=...

However: Using size for a discrete variable is not advised.

enter image description here