Removing Unused Subplot in R Plotly

笑着哭i 提交于 2020-12-13 03:37:25

问题


When using plotly (in R), after combining subplots there remains an unused and blank subplot. I've recreated the issue using the ggplot2 dataset mpg below.

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)
)

The only solution I've been able to find is tinkering with the width of the used subplot, but this leaves quite a bit of unused white space on the right and causes the title to be far off to the right (as it adjusts into the center of the used and unused subplots).

Is there a way to remove the unused subplot? If not, is there a way to organize/subset the dataframe such that only one plot needs to be used in the first place?

Thanks!


回答1:


You can assing the colours based on the manufacturer column:

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

This makes generating multiple subplots unnecessary.



来源:https://stackoverflow.com/questions/63001968/removing-unused-subplot-in-r-plotly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!