【问题标题】:Removing Unused Subplot in R Plotly删除 R Plotly 中未使用的子图
【发布时间】:2023-03-29 12:51:01
【问题描述】:

当使用 plotly(在 R 中)时,在组合子图后,仍然有一个未使用和空白的子图。我使用下面的 ggplot2 数据集mpg 重新创建了该问题。

library(dplyr)
library(ggplot2)
library(plotly)


audi <- mpg %>%
    filter(manufacturer == "audi")
chevy <- mpg %>%
    filter(manufacturer == "chevrolet")



fig1 <- plot_ly(audi, x = ~hwy, y = ~year, name = "", type = 'scatter',
             mode = "markers", marker = list(color = "blue", symbol = 'x-dot'))
fig2 <- plot_ly(chevy, x = ~hwy, y = ~year, name = "", type = 'scatter',
             mode = "markers", marker = list(color = "red", symbol = 'circle'))
fig <- subplot(fig1, fig2)
fig <- fig %>% subplot(shareX = TRUE,shareY = TRUE,which_layout = "merge")
fig <- fig %>% layout(
    title = "Audi and Chevy",
    xaxis = list(title = "Highway MPG"),
    yaxis = list(title = "Year"),
    margin = list(l = 100)
)

我能找到的唯一解决方案是修改使用的子图的宽度,但这会在右侧留下相当多未使用的空白区域,并导致标题远离右侧(因为它调整到已使用和未使用的子图的中心)。

有没有办法删除未使用的子图?如果没有,有没有办法组织/子集数据框,以便一开始只需要使用一个图?

谢谢!

【问题讨论】:

    标签: r plotly


    【解决方案1】:

    您可以根据制造商列分配颜色:

    data.subs <- mpg %>%
      filter(manufacturer == "audi" | manufacturer == "chevrolet")
    
    fig <- plot_ly(data.subs, x = ~hwy, y = ~year, name = "",
                   type = 'scatter', mode = "markers",
                   marker = list(color = factor(data.subs$manufacturer,
                                               labels = c("red", "blue")),
                                 symbol = 'circle'),
                   text = factor(data.subs$manufacturer,
                   labels = c("audi", "chevy")), hoverinfo = 'text'))
    
    fig <- fig %>% layout(
      title = "Audi and Chevy",
      xaxis = list(title = "Highway MPG"),
      yaxis = list(title = "Year"),
      margin = list(l = 100)
    )
    
    fig
    

    这使得生成多个子图变得不必要。

    【讨论】:

    • 谢谢!对于我的特定数据集,我需要两个类别的不同悬停文本。 IE。我需要雪佛兰说一件事,奥迪说另一件事。有没有办法用这种方法做到这一点?
    • 原理相同,但在 textoption 中。我已经更新了答案
    猜你喜欢
    • 1970-01-01
    • 2020-04-15
    • 2020-08-27
    • 2018-02-02
    • 2015-10-10
    • 1970-01-01
    • 2019-10-09
    • 2021-08-09
    • 2021-09-10
    相关资源
    最近更新 更多