R 如何绘制ggplot2散点图的特定颜色和形状?

R 如何绘制ggplot2散点图的特定颜色和形状?,r,colors,ggplot2,shapes,R,Colors,Ggplot2,Shapes,我一直在尝试使用ggplot2绘制散点图,其中的点都是一组自定义的颜色和形状,但没有得到我想要的 以下代码提供了正确的形状,但只有两种颜色(紫色和蓝色): 下面的代码仍然提供了正确的形状,但现在显示了颜色差异。但是,虽然需要不同颜色的点现在是不同的颜色,但它们不是正确的颜色。与我想要的颜色不同,它看起来使用了默认调色板 ggplot(dat, aes(x=dat$PC2, y=dat$PC3)) + geom_point(aes(color=factor(dat$color), shape

我一直在尝试使用ggplot2绘制散点图,其中的点都是一组自定义的颜色和形状,但没有得到我想要的

以下代码提供了正确的形状,但只有两种颜色(紫色和蓝色):

下面的代码仍然提供了正确的形状,但现在显示了颜色差异。但是,虽然需要不同颜色的点现在是不同的颜色,但它们不是正确的颜色。与我想要的颜色不同,它看起来使用了默认调色板

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")
我的颜色哪里出了问题?我尝试过从颜色切换到填充命令,但似乎无法获得正确的组合。是因为我重复颜色吗

下面是我试图绘制的数据样本(
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

非常感谢

问题是在打印之前必须设置因子级别,并且需要将颜色名称设置为字符向量:

# 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)
#按正确顺序设置dat$color的级别
dat$颜色

您不应该在
aes
内部重复
dat$
,因此
ggplot(dat,aes(x=dat$PC2,y=dat$PC3))+
应该是
ggplot(dat,aes(x=PC2,y=PC3))+
等等。这里的颜色不正确。例如,点(0.57,0.59)应该是红色的。谢谢@Jaap-这正是我想要的,我现在理解了我的错误。@george dontas thanx为我指出了错误,代码和绘图现在都正确了谢谢@george dontas!
# 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)
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")