R:Plotly和subplot():基于因子创建子图的最快方法 [英] R: Plotly and subplot(): fastest way to create a subplot based on a factor

查看:685
本文介绍了R:Plotly和subplot():基于因子创建子图的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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值的条形图.我想基于线有两个子图.我知道我可以做到:

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)

这是重复的,因为p1p2的代码基本相同.本地执行此操作最快的方法是什么?我知道facet_gridggplotly,但想在本地使用.

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.

谢谢:)

推荐答案

您可以split df,并构建每个图. 幸运的是,subplot支持列表,因此您可以将其全部通过管道发送

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)

仅使用基数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)

这篇关于R:Plotly和subplot():基于因子创建子图的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆