ggplot2 themes and background colors : The 3 elements
ggplot2文本:主题和背景色
本教程描述了如何使用R和ggplot2软件包更改绘图主题的外观(背景颜色,面板背景颜色和网格线)。 你还将学习如何使用ggplot2的基本主题以及如何创建自己的主题。
theme_gray :灰色背景色和白色网格线
theme_bw : 白色背景色和灰色网格线
theme_linedraw : 图周围的黑线
theme_light : 浅灰色的线条和轴(更多关注数据)
theme_minimal:无背景注释
theme_classic:具有轴线且没有网格线的主题
theme_void:空主题,对于具有非标准坐标的图或工程图很有用
theme_dark():深色背景旨在使颜色弹出
base_size:基本字体大小(更改所有绘图文本元素的大小)
base_family:基本字体系列
代码运行如下:
1. 自定义绘图背景的外观
rm(list = ls())
# Convert the column dose from numeric to factor variable
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
head(ToothGrowth)
library(ggplot2)
p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + geom_boxplot()
p
p + theme_gray(base_size = 14)
p + theme_bw()
p + theme_linedraw()
p + theme_light()
p + theme_minimal()
p + theme_classic()
p + theme_void()
p + theme_dark()
# Example 1
theme_set(theme_gray(base_size = 20))
ggplot(ToothGrowth, aes(x=dose, y=len)) + geom_boxplot()
# Example 2
ggplot(ToothGrowth, aes(x=dose, y=len)) + geom_boxplot()+
theme_classic(base_size = 25)
# Customize the appearance of the plot background
# Change the colors of plot panel background to lightblue
# and the color of grid lines to white
p + theme(
panel.background = element_rect(fill = "lightblue",
colour = "lightblue",
size = 0.5, linetype = "solid"),
panel.grid.major = element_line(size = 0.5, linetype = 'solid',
colour = "white"),
panel.grid.minor = element_line(size = 0.25, linetype = 'solid',
colour = "white")
)
# Remove plot panel borders and grid lines
p + theme(panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
# Hide panel borders and grid lines
# But change axis line
p + theme(panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(size = 0.5, linetype = "solid",
colour = "black"))
# Change the plot background color (not the panel)
p + theme(plot.background = element_rect(fill = "darkblue"))
2. 使用自定义主题
install.packages("ggthemes") # Install
library(ggthemes) # Load
# scatter plot
ggplot(mtcars, aes(wt, mpg)) +
geom_point() + geom_rangeframe() +
theme_tufte()
p <- ggplot(iris, aes(Sepal.Length, Sepal.Width, colour = Species))+
geom_point()
# Use economist color scales
p + theme_economist() +
scale_color_economist()+
ggtitle("Iris data sets")
p + theme_stata() + scale_color_stata() +
ggtitle("Iris data")
p + theme_wsj()+ scale_colour_wsj("colors6")+
ggtitle("Iris data")
p + theme_calc()+ scale_colour_calc()+
ggtitle("Iris data")
p + theme_hc()+ scale_colour_hc()