Reputation: 127
I've been trying to make a scatter plot using ggplot2 where the points are both a custom set of colors and shapes but haven't gotten exactly what I wanted.
The following code gives me the correct shapes, but only two colors (purple and blue):
ggplot(dat, aes(x=dat$PC2, y=dat$PC3)) +
geom_point(aes(color=dat$color, shape=dat$shape)) +
scale_colour_manual(values=dat$color) +
ggtitle("PC Scores") +
theme(legend.position="none")
The following code still gives me the correct shapes, but does now show color differentiation. But, while the points that need to be different colors are now different colors, they are not the right colors. Instead of the colors I want, it looks like it goes with a default palette.
ggplot(dat, aes(x=dat$PC2, y=dat$PC3)) +
geom_point(aes(color=factor(dat$color), shape=dat$shape)) +
scale_fill_manual(values=dat$color) +
ggtitle("PC Scores") +
theme(legend.position="none")
Where am I going wrong with the colors? I've tried switching from color to fill commands, but I just can't seem to get the right combination. Is it because I repeat colors?
Here is a sample of the data (dat
) I'm trying to plot:
PC2 PC3 color shape
-0.14 -0.22 purple 21
-0.04 -0.18 purple 21
0.12 -0.04 purple 21
0.34 0.08 blue 21
-0.06 -0.29 blue 21
0.13 -0.09 blue 21
0.02 0.02 blue 21
0.07 -0.12 orange 21
0.09 -0.10 orange 21
0.17 -0.06 orange 21
0.57 0.59 red 22
0.13 -0.01 red 22
0.26 0.19 red 22
0.18 0.07 red 21
0.13 -0.03 red 21
-0.19 -0.06 purple 22
-0.08 -0.04 purple 22
-0.03 -0.07 purple 22
0.12 -0.03 black 24
0.03 -0.19 black 24
0.11 -0.06 black 24
-0.42 0.29 blue 22
-0.63 0.39 blue 22
-0.57 0.32 blue 22
-0.23 0.16 blue 22
0.14 -0.05 purple 24
0.31 -0.15 purple 24
Thanks very much!
Upvotes: 4
Views: 9106
Reputation: 30445
ggplot(dat, aes(x=PC2, y=PC3)) +
geom_point(aes(color=color, shape=factor(shape))) +
scale_colour_manual(values= levels(dat$color)) +
ggtitle("PC Scores")
Upvotes: 4
Reputation: 83215
The problem is that you have to set the factor levels before plotting and you need to set the colornames as a character vector:
# set the levels of dat$color in the right order
dat$color <- factor(dat$color, levels = c("purple","blue","orange","red","black"))
# create a character vector of colornames
colr <- as.character(unique(dat$color))
ggplot(dat, aes(x=PC2, y=PC3)) +
geom_point(aes(color=color, shape=factor(shape))) +
scale_color_manual(breaks=unique(dat$color), values=colr)
this gives:
Note: I didn't remove the legend for illustrative reasons.
Upvotes: 7