每组/因子的 Plotly R 子面板

Mar*_*ark 1 plot r shiny plotly

我试图找到一个如何创建绘图的示例,其中为一列中的每个因素创建一个子面板,y 轴是值列,x 例如日期或行名

例如,如果我们采用mtcars数据框,分组cyl为每个 cyl 值创建 1 个子面板,绘制mpg为 y 轴和rownamex 轴

变量数量 此外,在我预期的情况下,我不知道会有多少个独特的因素,因为这取决于在绘图阶段之前在闪亮的应用程序中创建数据的模型。

我看到了这个示例,但是它为每个变量列绘制了一个面板,而不是每个因子绘制了一个面板:

p <- economics %>%
  tidyr::gather(variable, value, -date) %>%
  transform(id = as.integer(factor(variable))) %>%
  plot_ly(x = ~date, y = ~value, color = ~variable, colors = "Dark2",
          yaxis = ~paste0("y", id)) %>%
  add_lines() %>%
  subplot(nrows = 5, shareX = TRUE)
Run Code Online (Sandbox Code Playgroud)

如果有人知道如何让我开始或有一个关于如何执行此操作的现有示例,我将非常感激

编辑 我尝试构建此代码,但它似乎绘制了每个面板中的所有值

   mydf <- mtcars[ ,names(mtcars)[which(names(mtcars) %in%  c('cyl', 'mpg', 'hp'))]]
plot_ly(data = mydf, x =~hp, y=~mpg, type = 'scatter')


myplotlysub <- function(dat) {
  plot_ly(data = mydf, x =~hp, y=~mpg, type = 'scatter', mode = 'markers')
}

p <- mydf %>%
  group_by(cyl) %>%
  do(plot = myplotlysub(.)) %>%
  subplot(nrows = 1) %>%
  layout(
    showlegend = TRUE)
p
Run Code Online (Sandbox Code Playgroud)

面板但未校正

Ada*_*uer 6

使用ggplotly

完成该任务的一种可能方法是利用ggplot2&facet_grid然后使用 ggplot 对象将其转换为绘图对象plotly::ggplotly。该ggplotly功能并不总是很好,但如果您熟悉的话,ggplot2那么这是获得绘图的快速方法。请注意,由于返回的对象ggplotly是一个绘图对象,我们可以使用绘图函数进一步修改它。

library(ggplot2)
library(plotly)

# move rownames to a column for use in `aes()`
my_mtcars = mtcars
my_mtcars$model = rownames(my_mtcars)

# create ggplot
p = ggplot(my_mtcars, aes(x=model, y=mpg)) +
  geom_bar(stat='identity') +
  # facet by cyl (drop unused factors in a facet using free_x)
  facet_grid(. ~ cyl, scales = "free_x") +
  labs(x='') + 
  # rotate and size x tick marks
  theme(axis.text.x = element_text(angle = 90, 
                                   hjust = 1,
                                   size=5))
# add plotly-ness
ggplotly(p) %>% 
  layout(title="MPG by CYL")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

使用subplot

您也可以按照此SO Q/Aplotly::subplot中指出的方式使用。然而,答案使用了的公式语法,这似乎与plotly 对 , 的使用发生冲突,并导致错误。要运行没有错误,您可以避免使用plotly语法或使用而不是.purrr~~varlapplypurrr::map

subplotfacet_grid+相比的缺点ggplotly是最终会得到不同比例的 y 轴;如果您想避免混淆,则必须手动解决此问题。

library(plotly)
library(purrr)

# using purrr::map
mtcars %>% 
  split(mtcars$cyl) %>% 
  map(~{
    plot_ly(data = .x, 
            x = rownames(.x), 
            y = .x$mpg, 
            type = "bar")
  }) %>% 
  subplot(margin = .05)

# using lapply
mtcars %>% 
  split(mtcars$cyl) %>% 
  lapply(function(x) {
    plot_ly(data = x, 
            x = rownames(x), 
            y = ~mpg, 
            type = "bar")
  }) %>% 
  subplot(margin = .05)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述