R: Switching Between Graphs

不羁的心 提交于 2021-02-15 07:42:54

问题


I am using the R programming language. I am trying to follow the tutorial here on "switching between graphs" : https://plotly.com/r/dropdowns/ (first example).

First, I generated some data in R:

library(plotly)
library(MASS)

x <- sample( LETTERS[1:4], 1000, replace=TRUE, prob=c(0.25, 0.25, 0.25, 0.25) )
y <- rnorm(1000,10,10)
z <- rnorm(1000,5,5)
    
    df <- data.frame(x,y, z)
df$x = as.factor(df$x)
    colnames(df) <- c("x", "y", "z")

I tried to modify the code from this tutorial to make the final result:

fig <- plot_ly(df, x = ~x, y = ~y, z = ~z alpha = 0.3)
fig <- fig %>% add_markers(marker = list(line = list(color = "black", width = 1)))
fig <- fig %>% layout(
    title = "Drop down menus - Plot type",
    xaxis = list(domain = c(0.1, 1)),
    yaxis = list(title = "y"),
    updatemenus = list(
        list(
            y = 0.8,
            buttons = list(
                
                list(method = "restyle",
                     args = list("type", "scatter"),
                     label = "Scatter A"),
                
                list(method = "restyle",
                     args = list("type", "scatter"),
                     label = "Scatter B"),
                
                list(method = "restyle",
                     args = list("type", "scatter"),
                     label = "Scatter C"),
                
                list(method = "restyle",
                     args = list("type", "scatter"),
                     label = "Scatter D")
                
                
            ))

But this does not seem to be working.

Instead, I had a different idea: Perhaps I could create a series of graphs that I want to be able to "switch" between:

df_1 <- df[which(df$x == "A"),]
df_2 <- df[which(df$x == "B"),]
df_3 <- df[which(df$x == "C"),]
df_4 <- df[which(df$x == "D"),]


graph_1 <- plot_ly( data = df_1, type = "scatter", mode = "markers", x = ~ y, y = ~z) %>% layout(title = "graph 1")

graph_2 <- plot_ly( data = df_2, type = "scatter", mode = "markers", x = ~ y, y = ~z) %>% layout(title = "graph 2")

graph_3 <- plot_ly( data = df_3, type = "scatter", mode = "markers", x = ~ y, y = ~z) %>% layout(title = "graph 3")

graph_4 <- plot_ly( data = df_4, type = "scatter", mode = "markers", x = ~ y, y = ~z) %>% layout(title = "graph 4")

graph_5 <- plot_ly(df, y = ~y, color = ~x, type = "box") %>% layout(title = "boxplot")

Now, is it possible to modify the plotly code to "tie" all these graphs (graph_1, graph_2, graph_3, graph_4, graph_5) together, so that the user can click the tab on the left and switch between these graphs?

Thanks


回答1:


The example you should look at the tutorial is the last one (with the sine waves). It hides and shows different traces of the plot depending on the value of the selection in the dropdown menu.

You just need to change the format of your dataframe to wide.

df.wide <- df %>% tidyr::pivot_wider(names_from = x, values_from=z)

df.wide
## A tibble: 1,000 x 5
#       y     D     B       A     C
#   <dbl> <dbl> <dbl>   <dbl> <dbl>
# 1  6.48  6.21 NA    NA      NA   
# 2 23.6  NA    15.3  NA      NA   
# 3 -9.99 -2.16 NA    NA      NA   
# 4 19.6  NA    NA     0.0683 NA   
# 5 18.8  -1.40 NA    NA      NA   
# 6 -2.71  9.80 NA    NA      NA   
# 7  2.32 NA    NA    NA       3.77
# 8 11.9  NA     4.35 NA      NA   
# 9 21.4  NA    NA    NA      13.9 
#10  2.34 NA     2.10 NA      NA   
## … with 990 more rows

Then add a separate scatter trace for each column. In the arguments of the dropdown menu you can set which traces are going to be visible when each option is selected. For example args = list("visible", list(TRUE, FALSE, FALSE, FALSE)) means that only the first trace added (in this case column A) is going to be visible.

fig <- plot_ly(df.wide, x = ~y)
fig <- fig %>% 
  add_trace(y = ~A, name = "A", type='scatter', mode='markers') %>% 
  add_trace(y = ~B, name = "B", type='scatter', mode='markers', visible = F) %>%
  add_trace(y = ~C, name = "C", type='scatter', mode='markers', visible = F) %>%
  add_trace(y = ~D, name = "D", type='scatter', mode='markers', visible = F) %>% 
  layout(xaxis = list(domain = c(0.1, 1)),
         yaxis = list(title = "y"),
         updatemenus = list(
           list(
             y = 0.7,
             buttons = list(
               list(method = "restyle",
                    args = list("visible", list(TRUE, FALSE, FALSE, FALSE)),
                    label = "A"),
               list(method = "restyle",
                    args = list("visible", list(FALSE, TRUE, FALSE, FALSE)),
                    label = "B"),
               list(method = "restyle",
                    args = list("visible", list(FALSE, FALSE, TRUE, FALSE)),
                    label = "C"),
               list(method = "restyle",
                    args = list("visible", list(FALSE, FALSE, FALSE, TRUE)),
                    label = "D")))))

EDIT: Adding also a box plot

Adding an option for a different type of plot (like a box plot) is a little bit harder. The issue now is that x axis in the box plot and scatter plot are different. So you can't use the same axis. Fortunately, plotly lets you map different traces to different axis. Then you can set the position of this new axis within the complete plot using the domain attribute.

My solution is a little bit hacky because I used the domain attribute to "hide" the "plot" I did not want to use by making it very small (I also made the corresponding data invisible by setting visible = FALSE). This is because hiding the axis only hides the lines. You are still left with the background of the plot.

Note that now I use the method update (instead of restyle) because it allows you to change also the layout of the plot (https://plotly.com/r/custom-buttons/).

But it seemed to work very well!

# I had to reorder the dataframe because the boxplot was not following the order of the factors. Apparently it follows the orders that the letter appear.
df <- df %>% dplyr::arrange(x)

df.wide <- df %>% tidyr::pivot_wider(names_from = x, values_from=z)

# this is a list with axis config for scatter plot (define here to avoid repetition)
axis.config.scatter <- list(xaxis = list(title = "x", domain = c(0.1, 1), visible=T),
                            yaxis = list(title = "y", domain = c(0, 1), visible=T),
                            xaxis2 = list(title = "group", domain = c(0.99, 1), visible=F),
                            yaxis2 = list(title = "y", domain = c(0,99, 1), visible=F))

# this is a list with axis config for box plot (define here to avoid repetition)
axis.config.box <- list(xaxis = list(title = "x", domain = c(0.99, 1), visible=F),
                        yaxis = list(title = "y", domain = c(0.99, 1), visible=F),
                        xaxis2 = list(title = "group", domain = c(0.1, 1), visible=T, anchor='free'),
                        yaxis2 = list(title = "y", domain = c(0, 1), visible=T, anchor='free'))


fig <- plot_ly(df.wide)
fig <- fig %>% 
  add_trace(x = ~y, y = ~A, name = "A", type='scatter', mode='markers') %>% 
  add_trace(x = ~y, y = ~B, name = "B", type='scatter', mode='markers', visible = F) %>%
  add_trace(x = ~y, y = ~C, name = "C", type='scatter', mode='markers', visible = F) %>%
  add_trace(x = ~y, y = ~D, name = "D", type='scatter', mode='markers', visible = F) %>% 
  add_trace(data=df, x=~x, y=~z, name='box', type='box', visible=F, xaxis='x2', yaxis='y2') %>%
  layout(xaxis = list(title = "x", domain = c(0.1, 1)),
         yaxis = list(title = "y"),
         xaxis2 = list(title = "group", domain = c(0.99, 1), visible=F),
         yaxis2 = list(title = "y", domain = c(0.99, 1), visible=F),
         updatemenus = list(
           list(
             y = 0.7,
             buttons = list(
               list(method = "update",
                    args = list(list(visible = c(TRUE, FALSE, FALSE, FALSE, FALSE)),
                                axis.config.scatter),
                    label = "A"),
               list(method = "update",
                    args = list(list(visible = c(FALSE, TRUE, FALSE, FALSE, FALSE)),
                                axis.config.scatter),
                    label = "B"),
               list(method = "update",
                    args = list(list(visible = c(FALSE, FALSE, TRUE, FALSE, FALSE)),
                                axis.config.scatter),
                    label = "C"),
               list(method = "update",
                    args = list(list(visible = c(FALSE, FALSE, FALSE, TRUE, FALSE)),
                                axis.config.scatter),
                    label = "D"),
               list(method = "update",
                    args = list(list(visible = c(FALSE, FALSE, FALSE, FALSE, TRUE)),
                                axis.config.box),
                    label = "box")
               ))))



来源:https://stackoverflow.com/questions/66141967/r-switching-between-graphs

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