【问题标题】:Plotly: Putting y-axis two plots in the same range in PythonPlotly:在 Python 中将 y 轴两个图放在同一范围内
【发布时间】:2022-01-25 05:11:24
【问题描述】:

我有两个并排的箱形图,但我想让它们具有相同的 y 轴范围(在本例中为 150 - 400)。目前,右侧的图与左侧的 y 轴范围不同。我已经使用 fig.update_layout(yaxis_range=[140,410]) 进行了尝试,但我在这里没有任何成功。

剧情如下:

代码如下:

import plotly.graph_objects as go
import pandas as pd
import numpy as np
from plotly.subplots import make_subplots

df2 = pd.DataFrame()

np.random.seed(42)
df2['date'] = pd.date_range('2021-01-01', '2021-12-20', freq='D')
df2['month'] = df2['date'].dt.month
df2['spot_rate'] = np.random.randint(low=150, high=400, size=len(df2.index))

df4 = df2[df2['month'] == 12].tail(15)

fig = go.Figure()

fig = make_subplots(rows=1, cols=2, column_widths=[0.9, 0.1])

trendline = df2.groupby(['month']).spot_rate.median()
x1,y1 = list(trendline.index), trendline.values
stds = df2.groupby(['month']).spot_rate.std().values
n_vals = df2.groupby(['month']).date.count().values

## construct a 0.95 CI using mean ± z*std/sqrt(n)
y1_upper = list(y1 + 1.96*stds/np.sqrt(n_vals))
y1_lower = list(y1 - 1.96*stds/np.sqrt(n_vals))
y1_lower = y1_lower[::-1]

x1_rev = x1[::-1]

fig.add_trace(go.Scatter(x=x1, y=y1, line_shape="spline", line_color="blue", name="trendline"))

fig.add_trace(go.Scatter(
    x=x1+x1_rev,
    y=y1_upper+y1_lower,
    line_shape="spline",
    fill='toself',
    fillcolor='rgba(255,192,203,0.5)',
    line_color='rgba(255,255,255,0)',
    showlegend=False,
    name="0.95 CI",
))

fig.add_trace(go.Box(y = df2['spot_rate'],
                     x = df2['month'],
                     marker_color = '#6AF954',
                     name = 'Monthly'),
             row=1, col=1)

fig.add_trace(go.Box(y = df4['spot_rate'], 
                     x = df4['month'],
                     marker_color = "orange",
                     name = "Past 15 days"),
             row=1, col=2)

fig.update_layout(paper_bgcolor="black",
                    plot_bgcolor="black",#template="plotly_dark",
                  font_color="white",
                  title="Spot Rates by Time",
                  xaxis_title="Month",
                  yaxis_title="Spot Rate",
                 yaxis_range=[140,410])

fig.show()

【问题讨论】:

    标签: python plotly yaxis


    【解决方案1】:

    您可以将参数yaxis2 传递给update_layout 函数:

    fig.update_layout(yaxis2=dict(range=[140,410]))
    

    【讨论】:

      猜你喜欢
      • 2014-10-01
      • 2014-07-10
      • 2015-10-17
      • 2019-09-06
      • 2020-12-14
      • 2021-08-18
      • 2017-03-21
      • 1970-01-01
      • 2015-09-10
      相关资源
      最近更新 更多