R语言 ggplot2的主题和背景颜色

R语言 ggplot2的主题和背景颜色

在这篇文章中,我们将讨论如何使用R编程语言和ggplot2包来改变绘图主题的外观(背景色、面板背景色和网格线)。

ggplot2包中的主题

R语言中的ggplot2包有8个内置主题。要使用这些主题,我们只需要在绘图中添加该主题函数。这些函数通过操作绘图的三个关键方面,即背景色、面板背景色和网格线,来改变绘图的外观和感觉。

语法: plot + theme_function()

以下是R语言中ggplot2包中的8个预制主题。

  • theme_grey(): 创建一个灰色的背景颜色和没有边框的白色网格线。
  • theme_bw(): 创建一个白色背景和带有黑色边框的灰色网格线。
  • theme_linedraw(): 创建一个白色的背景颜色和黑色的网格线,并有一个黑色的厚边框。
  • theme_light(): 创建一个白色的背景和浅灰色的网格线,并带有浅灰色的边框。
  • theme_dark(): 创建一个深灰色的背景颜色和没有边框的灰色网格线。
  • theme_minimal(): 创建一个白色的背景颜色,没有网格线,也没有边框。
  • theme_classic(): 创建一个白色的背景颜色,没有网格线。它只有黑色的轴线。
  • theme_void(): 创建一个白色背景,没有边框、网格线或轴线。

例子

使用gridExtra软件包的grid.arrange函数,将所有8个主题结合起来的简单条形图。

# Create sample data
set.seed(5642)                             
sample_data <- data.frame(name = c("Geek1","Geek2",
                                   "Geek3","Geek4",
                                   "Geeek5") ,
                          value = c(31,12,15,28,45)) 
  
# Load ggplot2 package and gridExtra
library("ggplot2") 
library("gridExtra")
  
# Create bar plot using ggplot() function
basic_plot <- ggplot(sample_data,
             aes(name,value)) + 
geom_bar(stat = "identity")
  
# add theme function to plot all 8 themes
theme_grey <- basic_plot +
ggtitle("theme_grey")+
theme_grey()
  
theme_bw <- basic_plot+
ggtitle("theme_bw")+
theme_bw()
  
theme_linedraw <- basic_plot+
ggtitle("theme_linedraw")+
theme_linedraw()
  
theme_light <- basic_plot+
ggtitle("theme_light")+
theme_light()
  
theme_dark <- basic_plot+
ggtitle("dark")+
theme_dark()
  
theme_minimal <-basic_plot+
ggtitle("minimal")+
theme_minimal()
  
theme_classic <- basic_plot+
ggtitle("classic")+
theme_classic()
  
theme_void <- basic_plot+
ggtitle("theme_void")+
theme_void()
  
# arrange all the plots with different themes together
grid.arrange(theme_grey, theme_bw, theme_linedraw, theme_light, 
             theme_dark, theme_minimal, theme_classic, theme_void, 
             ncol = 4)

输出

R语言中ggplot2的主题和背景颜色

ggplot中的背景颜色

为了创建一个用户喜欢的手动主题,我们可以使用ggplot2包中theme函数的panel.background和plot.background参数来改变面板以及绘图的背景颜色。

语法: plot + theme(plot.background = element_rect( fill ) , panel.background = element_rect( fill ) )

例子

这里,是一个具有绿色面板背景和黄色情节背景颜色的条形图。

# Create sample data
set.seed(5642)                             
sample_data <- data.frame(name = c("Geek1","Geek2",
                                   "Geek3","Geek4",
                                   "Geeek5") ,
                          value = c(31,12,15,28,45)) 
  
# Load ggplot2 package
library("ggplot2") 
  
# Create bar plot using ggplot() function
# theme function is used to change the
# background colors of plot
ggplot(sample_data, aes(name,value)) + 
geom_bar(stat = "identity")+
theme(plot.background = element_rect(fill = "yellow"),
      panel.background = element_rect(fill = "green"))

输出

R语言中ggplot2的主题和背景颜色

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程