我试图在水平子图和共享 y 轴中输出折线图和条形图,但我只能输出 1 个,但不能同时输出两个。
import pandas as pd
import yfinance as yf
df = yf.download('SPY',period='1y')[['Adj Close','Volume']]
df['Bin'] = pd.cut(df['Adj Close'],bins=[200,225,250,275,300,325,350,375,400])
df_a = df.groupby('Bin')['Volume'].size().reset_index()
df_a['left'] = df_a['Bin'].apply(lambda x: x.left)
df_a.set_index('left',inplace=True)
fig, axes = plt.subplots(ncols=2, sharey=True)
df['Adj Close'].plot(ax=axes[0],kind='line') ## line 1
df_a['Volume'].plot(ax=axes[1],kind='barh') ## line 2
我尝试删除输出两个图形的 'sharey=True',但 y 轴未对齐。
答案 0 :(得分:0)
Matploblib 允许分别使用 Axes.twinx 和 Axes.twiny 方法为 X 轴和 Y 轴创建双轴。
使用以下代码,将两个图绘制在同一个图上。
fig, ax = plt.subplots()
volume_ax = ax.twiny()
adj_close_ax = ax.twinx()
df['Adj Close'].plot(ax=adj_close_ax,kind='line') ## line 1
df_a['Volume'].plot(ax=volume_ax,kind='barh', color='lightblue') ## line 2
答案 1 :(得分:0)