【发布时间】:2018-12-22 02:25:51
【问题描述】:
我正在创建一个绘图图,其中有一个按钮可以选择要显示的系列,这是一个非常基本的绘图功能。 我遇到的问题是该图的目的是显示可变性的差异和系列之间的差异增长率。 Plotly 根据正在绘制的系列的最大值/最小值自动设置每个轴的 ylim,这使得所有系列看起来都像 即使一个系列随时间增加 1 个单位,而另一个系列的趋势陡峭 5 倍,也会以相似的速度增加。我一直在尝试找到一种方法来定义特定于系列的 ylim 值,但找不到方法。 我知道我可以将每个系列相对化,但对于我的实际数据,绝对值非常重要。将所有线绘制在一个包罗万象的 ylim 中也不起作用,因为它会挤压我试图绘制的实际数据中的一些时间序列。
有人知道吗?
我正在尝试更改的实际图表是这项研究website。该图显示所有物种都以相同的速度增长,但事实并非如此......
以下是带有数据的示例代码和带有自动定义的 ylim 值的图形。请注意,由于 ylim 范围的巨大差异,所有迹线看起来都具有相同的趋势。
set.seed(0)
#create example dataframe
year=c(2000:2018)
grape_prices=c(seq(from=3.5, to=4.5, length.out = 19))+runif(19)
apple_prices=c(seq(from=3, to=5.5, length.out = 19))+runif(19)*2
mango_prices=c(seq(from=7, to=12, length.out = 19))
DF=data.frame(year, grape_prices, apple_prices, mango_prices)+runif(19)
#find ylims for each line that have roughtly the same range
DF_range_and_lims=as.data.frame(t(apply(DF[,-1], 2, range)))
names(DF_range_and_lims)=c("min", "max")
DF_range_and_lims$range=DF_range_and_lims$max-DF_range_and_lims$min
highest_range=DF_range_and_lims$range[which(DF_range_and_lims$range==max(DF_range_and_lims$range))]
cat("highest range is ", highest_range, "\n")
DF_range_and_lims$ylim_low=floor(DF_range_and_lims$min)
DF_range_and_lims$ylim_high=ceiling(DF_range_and_lims$min+highest_range)
DF_plot_ylims=DF_range_and_lims[,c("ylim_low", "ylim_high")]
cat("These are the ylims I would like to use", "\n")
DF_plot_ylims
#plotly plot with button for series selector
library(plotly)
ay <- list(
tickfont = list(color = "red"),
overlaying = "y",
side = "right")
multi_species_equal_axis <- plot_ly(DF, x = ~year) %>%
add_lines(y = ~grape_prices, name = "Grape prices") %>%
add_lines(y = ~apple_prices, name = "Apple_prices", visible=T, color = I('red'), yaxis = "y2") %>% #yaxis = "y2",
add_lines(y = ~mango_prices, name = "Mango Prices", visible=F, color = I('red'), yaxis = "y2") %>% #yaxis = "y2",
layout(
xaxis = list(title = "", domain = c(0.1, 1)),
updatemenus = list(
list(
buttons = list(
list(method = "restyle",
args = list("visible", list(TRUE, TRUE, FALSE)),
label = "Apple prices"),
list(method = "restyle",
args = list("visible", list(TRUE, FALSE, TRUE)),
label = "Mango prices")))),
yaxis2 = ay,
yaxis = list(rangemode="normal", title = "Price in R$"))
multi_species_equal_axis
【问题讨论】: