如何在R中使用ggplot2创建使用灰色调色板的类别散点图?


要使用ggplot2创建使用灰色调色板的类别散点图,我们可以按照以下步骤操作:

  • 首先,创建一个数据框。
  • 然后,创建具有默认点颜色的类别散点图。
  • 创建具有灰色调色板点颜色的类别散点图。

创建数据框

让我们创建一个如下所示的数据框:

 在线演示

x<-rnorm(25)
y<-rnorm(25)
Group<-sample(c("First","Second","Third"),25,replace=TRUE)
df<-data.frame(x,y,Group)
df

执行上述脚本后,将生成以下输出(由于随机化,此输出在您的系统上会有所不同):

       x           y        Group
1   0.03036902  -1.08989993 First
2  -1.36496321  -1.28054928 Third
3   0.23855417  -0.12276306 Third
4   0.52709378  -0.19730924 First
5  -1.24295750  -1.48467998 First
6  -0.57012334   0.70429757 Third
7  -2.23872847  -0.20110399 Third
8   0.51140516   0.14296460 First
9   0.55635303   0.20972904 Third
10  -0.24455115 -0.41292120 Third
11  0.38049399  -0.99364419 First
12  0.71502187   0.18136820 Third
13  -0.65251508 -0.09298097 First
14  -0.88401096  0.19342739 First
15  1.66023122   0.32843555 Second
16  -0.58101208 -0.49223091 First
17  -1.17912751 -0.69346144 Third
18  -0.75448095 -1.63278740 Third
19  -1.01581774 -0.05109014 Third
20  0.18852503  -2.13195617 First
21  -0.10338979  0.71512367 Second
22  1.83279352  -1.37538539 Second
23  -0.71975579 0.52236441  Third
24   0.12262292  0.81983890 First
25  -0.26669515 0.77764427  Second

创建类别散点图

加载ggplot2包并根据Group值创建类别散点图:

library(ggplot2)
x<-rnorm(25)
y<-rnorm(25)
Group<-sample(c("First","Second","Third"),25,replace=TRUE)
df<-data.frame(x,y,Group)
ggplot(df,aes(x,y,color=Group))+geom_point()

输出

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

创建使用灰色调色板的类别散点图

使用scale_color_grey函数创建类别点的散点图,这些点用灰色调色板着色:

library(ggplot2)
x<-rnorm(25)
y<-rnorm(25)
Group<-sample(c("First","Second","Third"),25,replace=TRUE)
df<-data.frame(x,y,Group)
ggplot(df,aes(x,y,color=Group))+geom_point()+scale_color_grey()

输出

更新于:2021年8月13日

153 次浏览

启动您的职业生涯

通过完成课程获得认证

开始
广告