如何在 R 中更改 ggplot2 图表的网格线颜色?


要更改 R 中 ggplot2 图表的网格线颜色,我们可以使用 theme 函数以及 panel.grid.major 和 panel.grid.minor 参数,在其中我们可以将绘图面板的次要和主要网格线颜色设置为所需的颜色。

要了解如何做到这一点,请查看下面的示例。

示例

以下代码片段创建了一个示例数据框 -

Open Compiler
x<-sample(0:9,20,replace=TRUE) y<-sample(0:9,20,replace=TRUE) df<-data.frame(x,y) df

创建了以下数据框

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

要加载 ggplot2 包并在上面创建的数据框上创建 x 和 y 之间的散点图,请将以下代码添加到上述代码片段中 -

x<-sample(0:9,20,replace=TRUE) y<-sample(0:9,20,replace=TRUE) df<-data.frame(x,y) library(ggplot2) ggplot(df,aes(x,y))+geom_point()

输出

如果您将所有上述代码片段作为单个程序执行,它将生成以下输出 -

要在上面创建的数据框上创建 x 和 y 之间的散点图,并在其中使用红色网格线,请将以下代码添加到上述代码片段中 -

x<-sample(0:9,20,replace=TRUE) y<-sample(0:9,20,replace=TRUE) df<-data.frame(x,y) library(ggplot2) ggplot(df,aes(x,y))+geom_point()+theme(panel.grid.major=element_line(colour="re d"),panel.grid.minor=element_line(colour="red"))

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

输出

如果您将所有上述代码片段作为单个程序执行,它将生成以下输出 -

更新于: 2021-11-02

4K+ 次浏览

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告