具有共享 y 轴的条形和线条子图

时间:2021-02-08 12:18:00

标签: pandas matplotlib

我试图在水平子图和共享 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
  1. 如何让两个图(共享 y 轴)一起出现? (第一张图是当我只有第 1 行时,第二张图是当我有第 1 行和第 2 行时)
  2. 如何使线图具有更长的 x 轴

我尝试删除输出两个图形的 'sharey=True',但 y 轴未对齐。

enter image description here

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:0)

Matploblib 允许分别使用 Axes.twinxAxes.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

Twin Y-Axis

答案 1 :(得分:0)

df.plot(kind='barh') 实际上根据范围索引绘制条形图,即 range(len(df)) 并重新标记轴刻度。您可以改用 plt.barh

fig, axes = plt.subplots(ncols=2, sharey=True)
df['Adj Close'].plot(ax=axes[0],kind='line') ## line 1 

# same height with bin width
axes[1].barh(df_a.index, df_a['Volume'], height=25) ## line 2

输出:

enter image description here