簡體   English   中英

在 R 中使用 for 循環使用 ggplot 創建多個圖形

[英]Using for loop to create multiple graphs with ggplot in R

我有看起來與此類似的數據:

Criteria         Person A      Person B     Person C      Person D
A                    10           15           12           11 
B                    50           55           40           37
C                    10           2             5           3 
D                    15           18           22           30 
E                    40           25           18           32
F                    12           35           10           12

我需要為每個條件創建一個 ggplot 柱形圖,但我想使用 for 循環來提高效率(或任何其他策略)。 一張圖表用於標准 A,一張圖表用於標准 B,依此類推。 所需的 output 應該類似於:

 ggplot(aes(x = person, y = n)) + geom_col() #for the criteria A
 ggplot(aes(x = person, y = n)) + geom_col() #for the criteria B
 ggplot(aes(x = person, y = n)) + geom_col() #for the criteria C
(...)

其中 x 是 A、B、C 和 D,n 是計數(10、15、12 ...)。 這個想法是為每個標准自動創建一個圖表,而不需要使用 filter() 手動創建和調整它們。

我已經找到了一些使用 facet_wrap 的選項,但這並不是我想要的。 在這種情況下,從 reshape2 熔化也不是一個選項,因為我想為每個標准創建不同的圖表。

有什么建議么?

這為每個“標准”創建了一個 plot

library(tidyverse)

sample_df <- data.frame(
  stringsAsFactors = FALSE,
  check.names = FALSE,
          Criteria = c("A", "B", "C", "D", "E", "F"),
          `Person A` = c(10L, 50L, 10L, 15L, 40L, 12L),
          `Person B` = c(15L, 55L, 2L, 18L, 25L, 35L),
          `Person C` = c(12L, 40L, 5L, 22L, 18L, 10L),
          `Person D` = c(11L, 37L, 3L, 30L, 32L, 12L)
)

sample_df %>% 
    pivot_longer(cols = -Criteria,
                 names_to = "person",
                 names_prefix = "Person\\s",
                 values_to = "n") %>% 
    group_nest(Criteria) %>% 
    mutate(plot = map(data, ~ggplot(.x, aes(x = person, y = n)) + geom_col())) %>% 
    pull(plot)
#> [[1]]

#> 
#> [[2]]

#> 
#> [[3]]

#> 
#> [[4]]

#> 
#> [[5]]

#> 
#> [[6]]

reprex package (v2.0.1) 創建於 2022-02-11

暫無
暫無

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

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