Using ggplot and ggplotly together

I have found that if I mix calls to ggplot and ggplotly together, only the last chart appears and overwrites the others or in some cases blocks the display of subsequent charts. I need to be able to produce some charts with ggplot and others with the interactive ggplotly.

Has anyone encountered this problem? Is there a way to perhaps reset the plot mechanism in RStudio without wiping out all of the plots (e.g., NOT dev.off())?

 library("ggplot2")
 library("plotly")
 test_data <- data.frame(A = c(1,5,7,4,2),
                         B = c(3,3,6,8,4),
                         C = c(6,2,9,4,5))

 my_dates <- as.Date(c("2010-01-01", "2010-02-01",
                       "2010-03-01", "2010- 4-01",
                       "2010-05-01"))

 xts_data <- xts(test_data, order.by = my_dates)
 p <- autoplot(xts_data, facets = NULL) +
   guides(color = guide_legend(override.aes = list(size = 2))) +
   geom_line(size = 1)
 print(ggplotly(p))

 new_df <- data.frame(P = c(70, 70, 70),
                    Category = c("A", "B", "C"),
                     Value = c(5, 15, 10))
p <- ggplot(data = new_df, aes(
      x = Category, y = Value)) +
      geom_bar(position = position_dodge(), stat = "identity")
 print(p)

Can you post a specific example of code and data that cause this problem? The best way to do that is as a Reproducible Example.

ggplot plot should go to plot pane, while ggplotly plot should go to view pane so they should not interfere with each other. You are using same variable for holding the ggplot object, so that will override each other obviously. Did you try different variable names or just use pipe to avoid temporary variable?

{ggplot call} %>% ggplotly
1 Like

I'm not sure what you mean by "plot pane" and "view pane." The windows of RStudio are: Source, Console, Environment/History, and Files/Plots. Which one is the view pane?

Tried the code you suggested and the piping doesn't produce any plot at all. Here is the modified code as suggested:

{ggplot(data = new_df, aes(
  x = Category, y = Value)) +
  geom_bar(position = position_dodge(), stat = "identity")} %>% ggplotly

If I add a print() around this statement I get the line graph but still get the overwrite by the bar chart.

UPDATE: ggplotly is going to the Viewer pane and ggplot is going to the Plot pane as outlined by andresrcs!!

image

1 Like

Yes! One of the plot shows up there. I have never used the Viewer before. Need to do some reading. Thanks for your help.

You also appear to be overwriting p. If you wish to retain both plot objects, just give them different names.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.