【问题标题】:R: Plotly and subplot(): fastest way to create a subplot based on a factorR:Plotly 和 subplot():基于因子创建子图的最快方法
【发布时间】:2017-03-17 12:57:48
【问题描述】:

我有一个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,但我想在剧情中原生地使用它。

谢谢你:)

【问题讨论】:

    标签: r plotly


    【解决方案1】:

    您可以split df,并构建每个情节。 幸运的是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)
    

    【讨论】:

    • 你好GGamba,谢谢。这看起来很棒。我是否正确理解 map 函数,它接受管道输入,这里是拆分的 df 并执行公式 ~{plot_ly(....)} 到它?如果这是一个愚蠢的问题,我很抱歉,我没有使用 purrr 包的经验,但它看起来非常有用。我想出了你的答案,把管道拿走了。你能解释一下~{}的用法吗?这对我来说是新的。非常感谢。
    • 另外,您是否知道如何调整两个图之间的间距,使刻度线不会像您的图片中那样重叠?谢谢:)
    • 这正是purrr 的工作原理。 ~.. 用于指定后面要应用的函数。在这种情况下,大括号{} 是多余的,因为它只是一个行函数。
    • 添加了base R 翻译和margin 以避免重叠
    • > p % + split(mtcars$cyl) %>% + map(~{ + plot_ly(data = .x, x = ~hp, y = ~mpg, type = "scatter") + }) %>% + subplot(margin = .05) as.list.environment(x, all.names = TRUE) 中的错误:...列表不包含 2 个元素 > p跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多