如何使用ggplot2更改R中的背景颜色?
在本文中,我们将讨论如何在 R 编程语言中更改 ggplot2 图的背景颜色。
首先,我们将创建一个基本的 ggplot2 图。
步骤 1:为绘图创建样本数据。
sample_data <- data.frame(x = 1:10, y = 1:10)
第 2 步:加载包 ggplot2。
library("ggplot2")
第 3 步:绘制一个基本的 ggplot2 图,没有任何颜色自定义。
ggplot(sample_data, aes(x, y)) + geom_point()
R
# load ggplot2
library("ggplot2")
# Create Sample data
sample_data <- data.frame(x = 1:10, y = 1:10)
# Draw plot with ggplot2
ggplot(sample_data, aes(x, y)) + geom_point()
R
# load ggplot2
library("ggplot2")
# Create Sample data
sample_data <- data.frame(x = 1:10, y = 1:10)
# Draw plot with changed theme using
# panel.background parameter
ggplot(sample_data, aes(x, y)) +
geom_point()+
theme(panel.background = element_rect(fill = "#00ab75" ))
R
# load ggplot2
library("ggplot2")
# Create Sample data
sample_data <- data.frame(x = 1:10, y = 1:10)
# Draw plot with changed theme using
# plot.background parameter
ggplot(sample_data, aes(x, y)) +
geom_point()+
theme(plot.background = element_rect(fill = "#00ab75" ))
R
# load ggplot2
library("ggplot2")
# Create Sample data
sample_data <- data.frame(x = 1:10, y = 1:10)
# Draw plot with changed theme using
# different prebuilt themes
ggplot(sample_data, aes(x, y)) + geom_point()+theme_dark()
输出:
更改背景面板的颜色
我们将使用ggplot2的参数 panel.background 来更改绘图面板的背景颜色。
ggplot(sample_data, aes(x, y)) + geom_point()+ theme(panel.background = element_rect(fill = “#00ab75”)
电阻
# load ggplot2
library("ggplot2")
# Create Sample data
sample_data <- data.frame(x = 1:10, y = 1:10)
# Draw plot with changed theme using
# panel.background parameter
ggplot(sample_data, aes(x, y)) +
geom_point()+
theme(panel.background = element_rect(fill = "#00ab75" ))
输出:
更改 ggplot2 中绘图的颜色
我们将使用 ggplot2 的参数 plot.background 来更改绘图的背景颜色。
ggplot(sample_data, aes(x, y)) + geom_point()+ theme(plot.background = element_rect(fill = “#00ab75”))
电阻
# load ggplot2
library("ggplot2")
# Create Sample data
sample_data <- data.frame(x = 1:10, y = 1:10)
# Draw plot with changed theme using
# plot.background parameter
ggplot(sample_data, aes(x, y)) +
geom_point()+
theme(plot.background = element_rect(fill = "#00ab75" ))
输出:
更改 ggplot2 中情节的整体主题
我们在 ggplot2 中有一些预先构建的主题,可用于更改 ggplot2 中的完整主题。 ggplot 中可用的主题是,
- 主题灰色
- 主题_bw
- theme_linedraw
- 主题光
- 主题暗
- theme_minimal
- 主题经典
- theme_void
- 主题测试
句法:
ggplot(sample_data, aes(x, y)) + geom_point()+ theme_dark()
电阻
# load ggplot2
library("ggplot2")
# Create Sample data
sample_data <- data.frame(x = 1:10, y = 1:10)
# Draw plot with changed theme using
# different prebuilt themes
ggplot(sample_data, aes(x, y)) + geom_point()+theme_dark()
输出: