R语言 改变Boxplot的轴标签

R语言 改变Boxplot的轴标签

箱形图是一种图表,它通过为每个人画出boxplots来显示分布形式的信息。Boxplots帮助我们按四分位数直观地显示数据的分布,并检测出异常值的存在。为Bowxplot添加轴标签将有助于Bowxplot的可读性。

在这篇文章中,我们将讨论如何在R编程语言中改变boxplot的轴标签。

方法1:使用基础R

在R编程语言中,通过使用 boxplot() 函数来创建膨胀图。

语法

boxplot(x, data, notch, varwidth, names, main)

参数

  • x: 该参数设置为一个向量或一个公式。
  • data : 该参数设置为数据框
  • notch: 该参数是横轴的标签。
  • varwidth: 这个参数是一个逻辑值。设置为 “true”,可以绘制与样本大小成比例的框的宽度。
  • main: 该参数是图表的标题。
  • names: 这个参数是将在每个boxplot下显示的组标签。

如果用基本R语言制作,我们使用 boxplot() 函数的 名称 参数。对于这个boxplot数据,首先要进行初始化,并将需要添加到坐标轴的名称作为向量传递。然后调用boxplot(),将数据和名称参数设置为该向量。

例子

# sample data for plotting
geeksforgeeks=c(120,26,39,49,15)
scripter=c(115,34,30,92,81)
writer=c(100,20,15,32,23)
  
# labels for Axis
label=c("geeksforgeeks","scripter","writer")
  
# boxplot with names parameter for labels
boxplot(geeksforgeeks, scripter, writer, names=label)
R

输出

在R中改变Boxplot的轴标签

带坐标轴标签的博列表

这也可以非常容易地用于水平博列表。为了将其转换为水平博列表,添加参数 Horizontal=True ,其余任务保持不变。为此,标签将出现在Y轴上。

例子

# sample data for plotting
geeksforgeeks=c(120,26,39,49,15)
scripter=c(115,34,30,92,81)
writer=c(100,20,15,32,23)
  
# labels for Axis
label=c("geeksforgeeks","scripter","writer")
  
# boxplot with names parameter for labels
boxplot(geeksforgeeks, scripter, writer, 
        names=label, horizontal=TRUE)
R

输出

在R中改变Boxplot的轴标签

带有更改过的标签的水平波谱图

方法2:使用ggplot2

如果使用 ggplot2 ,在绘制boxplot之前,我们先改变数据集本身的标签数据。

Reshape模块被用来将样本数据从宽格式转换为长格式,而ggplot2将被用来绘制boxplot。数据创建完毕后,使用melt函数将数据从宽格式转换为长格式。现在,改变数据集中的变量名称,并简单地绘制boxplot。

例子

# load package reshape2 and ggplot2
library("reshape2") 
library("ggplot2") 
  
# Create sample data 
set.seed(97364)                              
sample <- data.frame(x1 = rnorm(200),
                   x2 = rnorm(200, 2),
                   x3 = rnorm(200, 3, 3))
  
# Reshape sample data to long form
sample_main <- melt(sample)
  
# Add variable parameter for axis label in dataset
levels(sample_main$variable) <- c("geeksforgeeks","scripter","writer")
  
# Draw boxplot
ggplot(sample_main, aes(variable, value)) + 
geom_boxplot()
R

输出

在R中改变Boxplot的轴标签

带有更改过的标签的博列表

这可以非常容易地用于水平博列表。为了将其转换为水平博列表,在博列表代码中添加 coord_flip() ,其余部分与上面相同。

语法

geom_boxplot() + coord_flip()

例子

# load package reshape2 and ggplot2
library("reshape2") 
library("ggplot2") 
  
# Create sample data 
set.seed(97364)                              
sample <- data.frame(x1 = rnorm(200),
                   x2 = rnorm(200, 2),
                   x3 = rnorm(200, 3, 3))
  
# Reshape sample data to long form
sample_main <- melt(sample)
  
# Add variable parameter for axis label in dataset
levels(sample_main$variable) <- c("geeksforgeeks","scripter","writer")
  
# Draw boxplot
ggplot(sample_main, aes(variable, value)) + 
geom_boxplot() + coord_flip()
R

输出

在R中改变Boxplot的轴标签

使用ggplot2的水平boxplot,标签有所改变

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册