简体   繁体   中英

Removing Unused Subplot in R Plotly

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM