Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Legend position not preserved when converting ggplot2 to plotly #2407

Open
emilianomm opened this issue Dec 10, 2024 · 0 comments
Open

Legend position not preserved when converting ggplot2 to plotly #2407

emilianomm opened this issue Dec 10, 2024 · 0 comments

Comments

@emilianomm
Copy link

Description

When converting a ggplot2 plot to plotly using ggplotly(), the legend position specified in theme(legend.position=...) is not preserved in the resulting plotly graph. This requires additional layout configuration after conversion.

Reproducible Example

library(ggplot2)
library(plotly)

# Sample data
set.seed(123)
data <- data.frame(
  category = LETTERS[1:10],
  value = runif(10),
  group = factor(rep(1:2, 5))
)

# Create ggplot with specified legend position
p <- ggplot(data) +
  aes(x = category, y = value, fill = group) +
  geom_col() +
  theme(legend.position = "bottom")  # This position is not preserved

# Convert to plotly
p_interactive <- ggplotly(p)

# Current workaround needed
p_interactive <- ggplotly(p) %>%
  layout(
    legend = list(
      orientation = "h",
      x = 0.5,
      y = -0.2,
      xanchor = "center",
      yanchor = "top"
    )
  )

Expected Behavior

The legend position specified in the ggplot2 theme should be automatically translated to the equivalent plotly layout configuration.

Actual Behavior

The legend position from ggplot2 is ignored, and the legend defaults to plotly's default position (right side). Manual configuration using layout() is required to achieve the desired legend position.

Environment Information

  • R version: 4.4.2
  • The plot is rendered inside a Shiny App

Additional Context

This affects the workflow when converting static ggplot2 visualizations to interactive plotly graphs, requiring additional code to maintain consistent legend positioning. It would be helpful if the conversion process could automatically map ggplot2's legend positions to plotly's layout configurations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant