如何在R中使用ggplot2创建散点图,并根据变量更改点的形状和颜色?


一般来说,散点图中点的默认形状是圆形,但可以使用整数、序列或变量将其更改为其他形状。我们只需要在`geom_point`函数中使用`shape`参数并传递变量名即可。例如,如果我们想创建一个散点图,其中点的形状随变量x而变化,则可以使用`geom_point(shape=x)`。如果想改变大小,可以使用整数值。

示例

考虑以下数据框:

 在线演示

set.seed(151)
x<-rnorm(20,5,1)
y<-rnorm(20,5,2)
df<-data.frame(x,y)
df

输出

      x       y
1 4.948461 2.255857
2 5.765737 1.726474
3 4.853260 4.280697
4 4.886814 7.402230
5 4.604489 3.708252
6 5.782276 3.978782
7 3.602522 3.801754
8 3.981162 6.091206
9 5.229476 4.017412
10 5.672173 5.383071
11 4.515448 3.882945
12 5.560609 6.845399
13 5.066156 7.307996
14 3.650124 2.255179
15 4.757084 7.580363
16 3.763259 7.309804
17 3.525322 7.891359
18 7.437159 5.522026
19 5.673526 8.858292
20 5.310040 3.800228

加载ggplot2包并在x和y之间创建点图:

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

示例

library(ggplot2)
ggplot(df,aes(x,y))+geom_point()

输出

创建散点图,更改点的形状,大小设置为3:

示例

ggplot(df,aes(x,y))+geom_point(shape=x,color=x,size=3)

输出

更新于:2020年10月17日

474 次浏览

启动您的职业生涯

通过完成课程获得认证

开始学习
广告