使用 Plotly 的双 Y 轴和子图

问题描述 投票:0回答:1

我正在尝试生成一个图,其中在顶部绘制降雨量数据,在下面绘制两个位置的水位数据(使用双 Y 轴,因为两个位置的范围显着不同。

我已经成功地单独生成了这两个图,但是当使用

subplot
时,第二个水位时间序列图显示在上图上,并且所有轴标签都丢失了。

非常感谢您的帮助 1. 在子图的正确部分绘制第二个水位时间序列。 2. 正确绘制轴标签

#Set up left X axis
ay <- list(
  title = "Stream Level (cm)",
  zeroline = TRUE,
  showgrid = FALSE,
  range=c(0,30)
)

#Set up right Y axis
by <- list(
  tickfont = list(color = "red"),
  overlaying = "y",
  side = "right",
  title = "Bund Level (cm)",
  tick = 0,
  zeroline = TRUE,
  showgrid = FALSE,
  range=c(0,80)
)

#Plot water levels
p_30 <- ms_merged_30 %>%
  plot_ly() %>%
  add_lines(x = ~date, y = ~MS1_cm, name = "Stream_1 Level") %>%
  add_lines(x = ~date, y = ~MS2_cm, name = "Stream_2 Level", yaxis = "y2") %>%
  layout(
    title = "", yaxis = ay,  yaxis2 = by,
    xaxis = list(title="x")
  )

#Plot rainfall
rain_plot <- rain_data %>%
  plot_ly(type = "bar") %>%
  add_bars(x = ~DateTime, y = ~Rainfall, name = "Rainfall")

#Make subplot to combine hydrograph and hyteograph
combined_plot <- subplot(rain_plot, p_30, nrows = 2, heights = c(0.3,0.7), shareX = TRUE)

单独水位图 个别降雨量图 合并图,绘图错误

r plotly
1个回答
0
投票

我知道这是一个老问题,但在寻找答案时,我已经解决了同样的问题。

这是我的代码。我是巴西人,所以代码中的内容是葡萄牙语。但请密切关注解决方案。

====

fig = make_subplots(specs=[[{"secondary_y": True}]])

fig.add_trace(go.Scatter(x=df['datetime'], y=df['vazao'], name='vazão', mode='lines', showlegend=True), secondary_y=False)
fig.add_trace(go.Scatter(x=df['datetime'], y=df['chuva'], name='chuva', mode='lines', showlegend=True), secondary_y=True)

fig.update_yaxes(title=dict(text="vazão (m³/s)", font=dict(family="system-ui", size=18)), secondary_y=False)
fig.update_yaxes(title=dict(text="pluviometria (mm/dia)", font=dict(family="system-ui", size=18)), autorange="reversed", secondary_y=True)

fig.update_xaxes(title=dict(text="Período", font=dict(family="system-ui", size=18)))

fig.update_layout(autosize=True, height=1000, title_text="Hidrograma da estação")
fig.show()

hydrograph

© www.soinside.com 2019 - 2024. All rights reserved.