Interactively change axis scale (linear/log) in Plotly image using R

冷暖自知 提交于 2021-02-18 17:09:38

问题


Goal: To create interactive dropdown/buttons to update the axes' scale for a Plotly figure from R.

Issue: There is a lot of documentation on creating buttons and log plots using layout and updatemenus; however, it was difficult to find one that described how a button could be added specifically for changing the scale of the axes. Some posts on stackoverflow provided solutions for doing this in python but I struggled to find an equivalent one for R. I have provided a solution/example here based upon the python solution.

Starting Point: With a small sample data-set, I want to create a graphic that can have the scale change from linear to log and have different traces on the plots. I have provided my own solution, but if anyone else has a more creative solution feel free to add!

data <- data.frame(x = c(1, 2, 3), 
                   y = c(1000, 10000, 100000),
                   y2 = c(5000, 10000, 90000))


回答1:


Here is a solution based upon the one in python from the provided link; it was a bit tricky to know how deep to nest all of the lists. If you are not adding visibility to the traces, you can replace it with reference to the dataset.

library(plotly)
library(magrittr)

# Fake data
data <- data.frame(x = c(1, 2, 3), 
                   y = c(1000, 10000, 100000),
                   y2 = c(5000, 10000, 90000))

# Initial plot with two traces, one off
fig <- plot_ly(data) %>% 
  add_trace(x = ~x, y = ~y, type = 'scatter', mode = 'lines', name = 'trace1') %>%
  add_trace(x = ~x, y = ~y2, type = 'scatter', mode = 'lines', name = 'trace2', visible = F)

# Update plot using updatemenus, keep linear as first active, with first trace; second trace for log
fig <- fig %>% layout(title = 'myplot',
                      updatemenus = list(list(
                        active = 0,
                        buttons= list(
                          list(label = 'linear',
                               method = 'update',
                               args = list(list(visible = c(T,F)), list(yaxis = list(type = 'linear')))),
                          list(label = 'log',
                               method = 'update', 
                               args = list(list(visible = c(F,T)), list(yaxis = list(type = 'log'))))))))

The output looks like:



来源:https://stackoverflow.com/questions/60551262/interactively-change-axis-scale-linear-log-in-plotly-image-using-r

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