簡體   English   中英

R:Plotly和subplot():基於因子創建子圖的最快方法

[英]R: Plotly and subplot(): fastest way to create a subplot based on a factor

我有一個dataframe例如:

 line station   var
1       a 39446
1       b 82964
1       c 57840
1       d 78946
1       e 69972
1       f 14303
1       g 78179
2       a 37738
2       b 62261
2       c 19378
2       d 76435
2       e 17181
2       f 75148
2       g 10882

我想使用plot_ly從這些數據創建一個子圖。 我想要一個以station為x值,以var為y值的小節圖。 我想基於線有兩個子圖。 我知道我可以這樣做:

p1 <- plot_ly(data = df[df$line == "1", ], x = ~station, y = ~var, type = "bar")
p2 <- plot_ly(data = df[df$line == "2", ], x = ~station, y = ~var, type = "bar")
p3 <- subplot(p1, p2, nrows = 2)

這是重復的,因為p1p2的代碼基本相同。 本地執行此操作最快的方法是什么? 我知道facet_gridggplotly但我想在本地使用。

謝謝 :)

您可以split df,並構建每個圖。 幸運的是, subplot支持列表,因此您可以將其全部通過管道subplot

library(plotly)
library(purrr)

df %>% 
    split(df$line) %>% 
    map(~{
        plot_ly(data = .x, x = ~station, y = ~var, type = "bar")
    }) %>% 
    subplot(margin = .05)

在此處輸入圖片說明

僅使用基數R:

splitted_list <- split(df, df$line)

plot_list <- lapply(splitted_list, plot_ly, x = ~station, y = ~var, type = "bar")

subplot(plot_list, margin = .05)

暫無
暫無

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

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