AnteMeta
AnteMeta

Reputation: 47

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!

Upvotes: 1

Views: 409

Answers (1)

Julian_Hn
Julian_Hn

Reputation: 2141

You can assign 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.

Upvotes: 2

Related Questions