在同一图形上绘出直方图和折线图

2024-05-14 04:16:54 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,我正在尝试在同一个图形上绘制直方图和折线图,以创建MACD图表。但是,柱状图数据需要缩小,这样它就不会超过直线。有没有一种方法可以在不缩放数据帧中的数据的情况下缩小直方图enter image description here

t.head()

            Date    macd    macds   macdh
index               
0   2020-03-02  0.000000    0.000000    0.000000
1   2020-02-28  0.005048    0.002804    0.002244
2   2020-02-27  -0.000080   0.001622    -0.001702
3   2020-02-26  0.016184    0.006555    0.009629
4   2020-02-25  0.023089    0.011473    0.011615



fig = go.Figure()
fig.add_trace(go.Histogram(
            x=t['Date'],
            y=t['macdh'],

           ))

fig.add_trace(go.Scatter(
            x=t['Date'],
            y=t['macd'],

            line_color='dimgray',
            opacity=0.8))

fig.add_trace(go.Scatter(
            x=t['Date'],
            y=t['macds'],
            line_color='deepskyblue',
            opacity=0.8
            ))

fig.show()

Tags: 数据add图形godatelinefigtrace
1条回答
网友
1楼 · 发布于 2024-05-14 04:16:54

为了确保绝对不同的数据类别不会相互干扰,我更喜欢使用单独的子地块设置它们,而不是使用辅助y轴的混合绘图。下面是一个例子:

enter image description here

完整代码:

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

pio.templates.default = "plotly_white"
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')

fig = make_subplots(vertical_spacing = 0, rows=3, cols=1, row_heights=[0.6, 0.2, 0.2])

fig.add_trace(go.Candlestick(x=df['Date'],
                              open=df['AAPL.Open'],
                              high=df['AAPL.High'],
                              low=df['AAPL.Low'],
                              close=df['AAPL.Close']))

fig.add_trace(go.Scatter(x=df['Date'], y = df['mavg']), row=2, col=1)
fig.add_trace(go.Scatter(x=df['Date'], y = df['mavg']*1.1), row=2, col=1)
fig.add_trace(go.Bar(x=df['Date'], y = df['AAPL.Volume']), row=3, col=1)

fig.update_layout(xaxis_rangeslider_visible=False,
                  xaxis=dict(zerolinecolor='black', showticklabels=False),
                  xaxis2=dict(showticklabels=False))

fig.update_xaxes(showline=True, linewidth=1, linecolor='black', mirror=False)

fig.show()

相关问题 更多 >