如何在 R 中使用 ggplot2 更改部分绘图背景?


要更改部分绘图背景,我们可以使用 geom_rect 函数创建一个矩形,通过定义 alpha 和轴值来确定透明度,使用 fill 参数可以更改颜色。alpha 的值将完全隐藏灰色背景,我们可以根据需要调整其值。

示例

 实时演示

考虑以下数据框:

x<−rpois(20,5)
y<−rpois(20,5)
df<−data.frame(x,y)
df

输出

x y
1 5 4
2 4 5
3 4 3
4 6 2
5 7 5
6 2 4
7 3 8
8 7 5
9 2 3
10 5 3
11 7 7
12 5 4
13 8 2
14 6 4
15 3 8
16 2 9
17 5 2
18 8 5
19 2 8
20 6 6

加载 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()

输出

在绘图中创建一个矩形以更改绘图背景:

示例

ggplot(df,aes(x,y))+geom_point()+geom_rect(aes(xmin=3,xmax=7,ymin=0,ymax=10),fill="green",alpha=0.05)

输出

更新日期:2021 年 2 月 10 日

768 次浏览

开启你的职业生涯

通过完成课程获得认证

开始学习
广告