📜  在 R 中设置 ggplot2 绘图的轴中断

📅  最后修改于: 2022-05-13 01:55:37.279000             🧑  作者: Mango

在 R 中设置 ggplot2 绘图的轴中断

在本文中,我们将看到如何在 R 编程语言中设置 ggplot2 图的轴中断。

要在 R 中的 ggplot2 图中添加轴中断,我们使用 scale_x_break() 和 scale_y_break() 函数。这些函数将向量作为具有断点的参数。如果我们需要多个断点,我们也可以添加它们。

示例 1:在 ggplot2 绘图中指定 X 轴刻度

这是使用 scale_x_continuous()函数的x 轴中断的 ggplot2 散点图。这个函数有一个breaks参数,它以一个向量作为输入,该向量将所有轴中断点作为向量点。因此,在这里我们可以手动将轴断点设置为绘图。

代码:

R
# Create sample data
set.seed(5642)   
sample_data <- data.frame(x = rnorm(1000),        
                    y = rnorm(1000))
# Load ggplot2 and ggbreak
library("ggplot2") 
library("ggbreak") 
  
# create plot with axis break
ggplot(sample_data, aes(x = x, y = y)) 
+ geom_point() + scale_x_continuous(breaks = c(-1,0, 1))


R
# Create sample data
set.seed(5642)   
sample_data <- data.frame(x = rnorm(1000),        
                    y = rnorm(1000))
# Load ggplot2 and ggbreak
library("ggplot2") 
library("ggbreak") 
  
# create plot with axis break
ggplot(sample_data, aes(x = x, y = y)) 
+ geom_point() + scale_y_continuous(breaks = c(-2, -1, 0, 1))


R
# Create sample data
set.seed(5642)   
sample_data <- data.frame(x = rnorm(1000),        
                    y = rnorm(1000))
  
# Load ggplot2 and ggbreak
library("ggplot2") 
library("ggbreak") 
  
# create plot with axis break
ggplot(sample_data, aes(x = x, y = y)) 
+ geom_point() + scale_x_continuous(breaks = seq(-3, 4, 0.2))


输出:

示例 2:在 ggplot2 绘图中指定 Y 轴刻度

这是使用 scale_y_continuous()函数的y 轴中断的 ggplot2 散点图。这个函数有一个breaks参数,它以一个向量作为输入,该向量将y轴break的所有点作为向量点。因此,在这里我们可以手动将轴断点设置为绘图。

电阻

# Create sample data
set.seed(5642)   
sample_data <- data.frame(x = rnorm(1000),        
                    y = rnorm(1000))
# Load ggplot2 and ggbreak
library("ggplot2") 
library("ggbreak") 
  
# create plot with axis break
ggplot(sample_data, aes(x = x, y = y)) 
+ geom_point() + scale_y_continuous(breaks = c(-2, -1, 0, 1))

输出:



示例 3:在 ggplot2 图中指定轴刻度的序列

为了指定轴刻度的序列,我们使用 seq函数作为参数来破坏 scale_x_continuous / scale_y_continuous 而不是向量的属性。这里不是将输入作为向量给出,而是将输入作为具有三个点的序列给出,第一个是开始中断,第二个是结束中断,第三个是开始和结束中断之间的中断时间段。

代码:

电阻

# Create sample data
set.seed(5642)   
sample_data <- data.frame(x = rnorm(1000),        
                    y = rnorm(1000))
  
# Load ggplot2 and ggbreak
library("ggplot2") 
library("ggbreak") 
  
# create plot with axis break
ggplot(sample_data, aes(x = x, y = y)) 
+ geom_point() + scale_x_continuous(breaks = seq(-3, 4, 0.2))

输出: