R语言 如何用fct_reorder给boxplot中的方框排序

R语言 如何用fct_reorder给boxplot中的方框排序

在这篇文章中,我们将讨论如何使用R编程语言中的fct_reorder()函数在boxplot中重新排序方框。

默认情况下,ggplot2的boxplot是按照分类变量的字母顺序排列方框的。但是为了更好地可视化数据,有时我们需要将它们重新排序。为了将数据按升序或降序排序,我们使用forcats包的fct_reorder()函数。R语言的forcats包包含用于重新排序和修改因子水平的助手。fct_reorder()函数帮助我们通过与另一个变量一起排序来重新排列因子水平。

方法1:以升序方式重新排序boxplot

fct_reorder()函数默认以value_variable的升序对数据进行排序。因此,我们使用fact_reorder()函数首先将数据按升序排序。然后我们使用ggplot2包的geom_boxplot()函数来绘制boxplot。

语法: df %>% mutate( categorical_variable= fct_reorder( categorical_variable, value_variable))

参数

  • df: 决定用于重新排序数据的数据框架。
  • categorical_variable: 决定了要重新排序的变量。
  • value_variable: 确定要重新排序的数据的变量。

安装和导入tidyverse软件包的语法

install.package('tidyverse')    # To install
library(tidyverse)              # To import  
Bash

例子

这里,是一个基本的boxplot,方框按升序排序。在这个例子中使用的CSV可以在这里下载。

# load library tidyverse
library(tidyverse)
  
# load sample data
sample_data <- read.csv("sample_box.CSV")
  
# Reorder data with fct_reorder function 
# and plot boxplot
sample_data <- sample_data%>%mutate(Brand=fct_reorder(Brand, Result))
  
# plot boxplot
ggplot(sample_data, aes(x=Result, y=Brand))+
          geom_boxplot()
Bash

输出

如何在R语言中用fct_reorder给boxplot中的方框排序?

方法2:以降序重新排列boxplot

为了按降序重新排列数据,我们使用fct_reorder()函数的.desc参数。当.desc参数为真时,将数据按降序排序,默认情况下,它是假的,因此将数据按升序排序。

语法: df %>% mutate( categorical_variable= fct_reorder( categorical_variable, value_variable, .desc))

参数

  • .desc: 决定了一个布尔值,如果为真,将数据按降序排序。默认情况下,它是假的。

例子

这里,是一个基本的boxplot,其方框按降序排序。

# load library tidyverse
library(tidyverse)
  
# load sample data
sample_data <- read.csv("sample_box.CSV")
  
# Reorder data with fct_reorder function 
# and plot boxplot
sample_data <- sample_data%>%mutate(Brand=fct_reorder(
  Brand, Result, .desc=TRUE))
  
# plot boxplot
ggplot(sample_data, aes(x=Result, y=Brand))+
          geom_boxplot()
Bash

输出

如何在R语言中用fct_reorder给boxplot中的方框排序?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册