我有一个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
Run Code Online (Sandbox Code Playgroud)
我想使用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)
Run Code Online (Sandbox Code Playgroud)
这是一种重复的,因为代码p1和p2基本相同。本地执行此操作最快的方法是什么?我知道的facet_grid和ggplotly,但希望它本身在plotly。
谢谢 :)
您可以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)
Run Code Online (Sandbox Code Playgroud)
仅使用基数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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
927 次 |
| 最近记录: |