使用 R 在 Plotly 图像中交互式更改轴比例 (linear/log)
Interactively change axis scale (linear/log) in Plotly image using R
目标: 创建交互式 dropdown/buttons 以更新来自 R 的 Plotly 图的坐标轴比例。
问题: 有很多关于创建 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 Whosebug provided solutions for doing this in 的文档,但我很难找到 R 的等效文档。我提供了 solution/example这里基于 python 解决方案。
起点: 对于一个小样本数据集,我想创建一个图形,其比例可以从线性变为对数,并且在绘图上有不同的轨迹。我已经提供了自己的解决方案,但如果其他人有更好的解决方案,请随时添加!
data <- data.frame(x = c(1, 2, 3),
y = c(1000, 10000, 100000),
y2 = c(5000, 10000, 90000))
这是一个基于 python 中提供的 中的解决方案;要知道所有 list
的嵌套深度有点棘手。如果您不为轨迹添加可见性,您可以将其替换为对数据集的引用。
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'))))))))
输出如下:
目标: 创建交互式 dropdown/buttons 以更新来自 R 的 Plotly 图的坐标轴比例。
问题: 有很多关于创建 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 Whosebug provided solutions for doing this in
起点: 对于一个小样本数据集,我想创建一个图形,其比例可以从线性变为对数,并且在绘图上有不同的轨迹。我已经提供了自己的解决方案,但如果其他人有更好的解决方案,请随时添加!
data <- data.frame(x = c(1, 2, 3),
y = c(1000, 10000, 100000),
y2 = c(5000, 10000, 90000))
这是一个基于 python 中提供的 list
的嵌套深度有点棘手。如果您不为轨迹添加可见性,您可以将其替换为对数据集的引用。
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'))))))))
输出如下: