繁体   English   中英

Plotly:如何更改子图的 y 轴范围?

[英]Plotly: How to change the range of the y-axis of a subplot?

我有以下代码:

from plotly.subplots import make_subplots
import requests 
import json
import datetime as dt
import pandas as pd
import plotly.graph_objects as go




def get_candles(symbol, window, interval='1h'):
    url = "https://api.binance.com/api/v1/klines"
    end_time = dt.datetime.utcnow()
    delta = dt.timedelta(hours = window)
    start_time = end_time - delta
    start_date = str(int(start_time.timestamp() * 1000))
    end_date = str(int(end_time.timestamp() * 1000))
    limit = '1000'
    market = symbol + 'BUSD'

    req_param = {"symbol": market, "interval": interval, "startTime": start_date, "endTime": end_date, "limit": limit}

    text = requests.get(url, params = req_param).text
    data = json.loads(text)
    df = pd.DataFrame(data)
    df.columns = ['open_time',
                    'o', 'h', 'l', 'c', 'v',
                    'close_time', 'qav', 'num_trades',
                    'taker_base_vol', 'taker_quote_vol', 'ignore']

    df.index = [dt.datetime.fromtimestamp(x/1000.0) for x in df.close_time]

    return df


def chart(symbol, interval='1h'):
    windows = {'1m': 1, '5m': 5, '15m': 15, '30m': 30, '1h': 60, '2h': 120, '4h': 240, '6h': 360, '12h': 720, '1d': 1440}
    chart = get_candles(symbol.upper(), windows[interval], interval)
    fig = make_subplots(specs=[[{"secondary_y": True}]])
    print(chart['v'].max())
    fig.add_trace(go.Candlestick(x=chart.index,
            open=chart['o'],
            high=chart['h'],
            low=chart['l'],
            close=chart['c'],
            name="yaxis1 data",
            yaxis='y1'), secondary_y=True)
    fig.add_trace(go.Bar(x=chart.index, y=chart['v'], name="yaxis2 data", yaxis="y2"), secondary_y=False)
    fig.layout.yaxis2.showgrid=False
    fig.update_yaxes(type="linear")
    fig.update_layout(xaxis_rangeslider_visible=False)
    
    # fig.show()

    fig.write_image("figure.png", engine="kaleido")
    
chart('bnb')

它产生以下图像: 此代码生成的图表

现在我想要它,以便音量条仅达到图表总高度的 1/3,我尝试这样做:

fig.update_layout(yaxis1=dict(title="bars", domain=[0, int(2* chart['v'].max())]))

但这没有任何作用。

如何给某个 y 轴命名并更改其范围?

这是这样的:

fig.update_layout(yaxis2 = dict(range=[<from_value>, <to_value>]))

您的代码示例对我不起作用。 但在此示例中,以下设置:

fig.update_layout(yaxis2 = dict(range=[0, 300*10**6]))

...将变成这样:

在此处输入图像描述

...进入这个:

在此处输入图像描述

完整代码:

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

# data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')

# Create figure with secondary y-axis
fig = make_subplots(specs=[[{"secondary_y": True}]])

# include candlestick with rangeselector
fig.add_trace(go.Candlestick(x=df['Date'],
                open=df['AAPL.Open'], high=df['AAPL.High'],
                low=df['AAPL.Low'], close=df['AAPL.Close']),
               secondary_y=False)

# include a go.Bar trace for volumes
fig.add_trace(go.Bar(x=df['Date'], y=df['AAPL.Volume']),
               secondary_y=True)
f = fig.full_figure_for_development(warn=False)

fig.layout.yaxis2.showgrid=False
fig.update_layout(yaxis2 = dict(range=[0, 300*10**6]))
fig.show()

我不使用plotly ,但是查看文档,我看到以下设置y轴范围的内容:

Code: fig.update_yaxes(range=<VALUE>)
Type: list

https://plotly.com/python/reference/layout/yaxis/#layout-xaxis-range

对于标签/标题:

Code: fig.update_yaxes(title=dict(...))
Type: dict containing one or more of the keys listed below.

fig.update_layout(title_text=<VALUE>)

https://plotly.com/python/reference/layout/yaxis/#layout-yaxis-title

我有一个与此类似的问题,但上面的答案没有帮助,因为我的图表是动态的。 根据时间范围,最大交易量可能在 300 - 1000 万之间,因此固定范围并不好。

似乎最好的解决方案是使用 max() 函数在我的数据框的体积列中找到最大值(也是动态的):

maxVol = max(df['Volume'], key=float)
ymax = float(maxVol)
print(ymax)

然后只需使用以下内容将最大范围缩放 3 倍

fig.update_layout(yaxis=dict(range=[0, ymax*3]))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM