Ros*_*920 3 r colors shapes ggplot2
我一直在尝试使用ggplot2制作一个散点图,其中这些点既是一组自定义的颜色和形状,但却没有得到我想要的.
以下代码为我提供了正确的形状,但只有两种颜色(紫色和蓝色):
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")
Run Code Online (Sandbox Code Playgroud)
下面的代码仍然给我正确的形状,但现在显示颜色差异.但是,虽然需要不同颜色的点现在是不同的颜色,但它们不是正确的颜色.它取代了我想要的颜色,看起来像是默认调色板.
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")
Run Code Online (Sandbox Code Playgroud)
我哪里出错了颜色?我尝试从颜色切换到填充命令,但我似乎无法获得正确的组合.是因为我重复了颜色吗?
这是dat我试图绘制的数据样本():
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
Run Code Online (Sandbox Code Playgroud)
非常感谢!
问题是您必须在绘图之前设置因子级别,并且需要将颜色名称设置为字符向量:
# 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)
Run Code Online (Sandbox Code Playgroud)
这给了:
注意:出于说明原因,我没有删除图例.