如何在 R 中使用 ggplot2 更改散点图中点的颜色?


若要使用 ggplot2 更改散点图中点的颜色,我们可以在 geom_point 内使用具有 aes 的 colour 参数。颜色的传递方式有几种,一种方式是指定特定颜色,另一种方式是给出范围或使用变量。如果使用范围或变量,那么点的颜色将采用不同的色调。

示例

 演示

考虑以下数据框 −

x<−rnorm(20,5,2)
y<−rnorm(20,5,1.25)
df<−data.frame(x,y)
df

输出

      x       y
1 6.3184535 5.548867
2 3.4643698 6.247067
3 7.8930528 2.259042
4 7.6517535 4.606704
5 1.7838941 3.605288
6 0.3985215 6.183794
7 5.2738435 3.857376
8 4.7734419 3.389663
9 3.9727197 5.662962
10 3.3976335 5.172815
11 4.1068840 4.379264
12 6.7723590 5.914132
13 3.0944360 4.184177
14 7.0857100 5.266121
15 2.6391362 4.433864
16 5.2571231 4.144391
17 5.8119542 4.725406
18 5.3608015 4.828909
19 9.7308286 6.489042
20 2.3823201 6.916862

加载 ggplot2 包并创建一个散点图 −

library(ggplot2)
ggplot(df,aes(x,y,col=x))+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.

输出

使用变量 x 创建散点图 −

示例

ggplot(df,aes(x,y))+geom_point(aes(colour=x))

输出

更新于:05-Feb-2021

19K+ 浏览次数

开启你的 职业生涯

完成课程并获得认证

开始
广告