簡體   English   中英

帶有數字和分類變量的框 plot

[英]Box plot with numeric and categorical variables

我想創建一個框 plot 來可視化具有相同比例的多個數值變量相對於一個分類變量的分布,以便查看針對某個特定水平的因子的不同度量之間的行為。

例如,我想查看 3 位客戶訂購的貨物數量(以千美元計)與產品類型的差異有多大。 以這個示例數據為例:

prueba <- data.frame("client1" = truncnorm::rtruncnorm(n = 60, a = 1, b = 9.8, mean = 6.5, sd = 1),
                     "client2" = truncnorm::rtruncnorm(n = 60, a = 1, b = 9.8, mean = 6.9, sd = 2),
                     "client3" = truncnorm::rtruncnorm(n = 60, a = 1, b = 9.8, mean = 5, sd = 3),
                     "type" = as.factor(sample(LETTERS[1:3], 60, replace = T, prob = c(0.4,0.35,0.25))),
                     "cat" = as.factor(sample(LETTERS[20:22], 60, replace = T, prob = c(0.5, 0.1,0.4))))
prueba[,1:3] <- round(prueba[,1:3], 1)
head(prueba)
#  client1 client2 client3 type cat
#1     6.3     7.2     7.0    B   T
#2     7.2     6.5     3.5    C   T
#3     8.0     6.4     8.0    A   V
#4     8.0     7.4     7.0    A   V
#5     7.5     7.6     2.5    B   V
#6     7.0     9.0     3.7    A   V

使用 ggplot 我可以做到這一點:

library(tidyverse)
library(patchwork)

uno <- prueba %>% ggplot(aes(x = type, 
                      y = client1)) +
        geom_boxplot()+scale_y_continuous(limits = c(0,10))

dos <- prueba %>% ggplot(aes(x = type, 
                             y = client2)) +
        geom_boxplot()

tres <- prueba %>% ggplot(aes(x = type, 
                              y = client3)) +
        geom_boxplot()

uno+dos+tres+plot_layout(byrow = F)

我明白了: 分布差異:
分布差異

但是,我想要這樣的東西: 像這樣的東西:
像這樣的東西

但不是 x 軸填充其他類別,我希望它填充每個客戶端的分布。

  1. 這可能嗎?

  2. 如何在 R 中執行此操作?

  3. 還有其他可視化方法可以做到這一點嗎?

你在尋找這樣的東西嗎?

prueba2 <- prueba %>% 
  pivot_longer(cols = starts_with("client"), names_to = "client")

  ggplot(data = prueba2, aes(x = type, 
                             y = value, 
                             fill = client)) +
  geom_boxplot() 

在此處輸入圖像描述

如果是這樣,首先將所有 client# 列放入一個“client”列,並將相應的值放入另一個帶有 pivot_longer 的列“value”(來自 package tidyr,已經在 tidyverse 中)。 然后讓 ggplot 執行 rest - 我們只需要告訴它:x 軸是“類型”,y 軸是“值”,“客戶端”是填充顏色。

我不確定我是否正確理解您,但如果您想要每個級別的客戶端而不是每個級別的 cat,那么您必須將所有內容轉換為長格式:

prueba <- data.frame("client1" = truncnorm::rtruncnorm(n = 60, a = 1, b = 9.8, mean = 6.5, sd = 1),
                     "client2" = truncnorm::rtruncnorm(n = 60, a = 1, b = 9.8, mean = 6.9, sd = 2),
                     "client3" = truncnorm::rtruncnorm(n = 60, a = 1, b = 9.8, mean = 5, sd = 3),
                     "type" = as.factor(sample(LETTERS[1:3], 60, replace = T, prob = c(0.4,0.35,0.25))),
                     "cat" = as.factor(sample(LETTERS[20:22], 60, replace = T, prob = c(0.5, 0.1,0.4))))
prueba[,1:3] <- round(prueba[,1:3], 1)

library(reshape2)

prueba_long <- melt(prueba,  id.vars = c('type', 'cat'))

ggplot(prueba_long, aes(x = type, y = value, colour = variable)) +
  geom_boxplot()

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM