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

我只是一个虾纸丫 提交于 2019-12-23 03:43:13

问题


I have a dataframe such as:

 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

I would like to use plot_ly to create a subplot from these data. I want a barplot with station as x-values, and var as y-values. I want to have two subplots based on line. I know that I could just do:

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)

This is kind of repetitive because the code for p1and p2 is basically the same. What is the fastest way to do this natively? I am aware of facet_gridand ggplotlybut would like to it natively in plotly.

Thank you :)


回答1:


You can split the df, and build each plot. Luckily subplot supports list and so you can pipe it all:

library(plotly)
library(purrr)

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

Using only base 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)


来源:https://stackoverflow.com/questions/42858202/r-plotly-and-subplot-fastest-way-to-create-a-subplot-based-on-a-factor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!