使用DataFrame.Plot在同一图上绘制多个图

时间:2014-06-15 07:59:11

标签: python matplotlib pandas

虽然我可以在图表上获得多行并在图表上显示多个条形图 - 但我无法使用相同的PeriodIndex在同一图表上获得一条直线和条形。

虚假代码如下......

# play data
n = 100
x = pd.period_range('2001-01-01', periods=n, freq='M')
y1 = (Series(np.random.randn(n)).diff() + 5).tolist()
y2 = (Series(np.random.randn(n)).diff()).tolist()
df = pd.DataFrame({'bar':y2, 'line':y1}, index=x)

# let's plot
plt.figure()
ax = df['bar'].plot(kind='bar', label='bar')
df['line'].plot(kind='line', ax=ax, label='line')
plt.savefig('fred.png', dpi=200)
plt.close()

任何帮助将不胜感激......

1 个答案:

答案 0 :(得分:4)

问题是:条形图不能将索引值用作x轴,而是使用range(0, n)。您可以使用twiny()创建第二个与轴条轴共用y轴的轴,并在第二个轴上绘制直线曲线。

最困难的是如何对齐x轴刻度。在这里,我们定义了对齐函数,它将ax2.get_xlim()[0]中的x1ax1中的ax2.get_xlim()[1]x2中的ax1 def align_xaxis(ax2, ax1, x1, x2): "maps xlim of ax2 to x1 and x2 in ax1" (x1, _), (x2, _) = ax2.transData.inverted().transform(ax1.transData.transform([[x1, 0], [x2, 0]])) xs, xe = ax2.get_xlim() k, b = np.polyfit([x1, x2], [xs, xe], 1) ax2.set_xlim(xs*k+b, xe*k+b) 对齐:

from matplotlib import pyplot as plt
import pandas as pd
from pandas import Series
import numpy as np
n = 50
x = pd.period_range('2001-01-01', periods=n, freq='M')
y1 = (Series(np.random.randn(n)) + 5).tolist()
y2 = (Series(np.random.randn(n))).tolist()
df = pd.DataFrame({'bar':y2, 'line':y1}, index=x)

# let's plot
plt.figure(figsize=(20, 4))
ax1 = df['bar'].plot(kind='bar', label='bar')
ax2 = ax1.twiny()
df['line'].plot(kind='line', label='line', ax=ax2)
ax2.grid(color="red", axis="x")

def align_xaxis(ax2, ax1, x1, x2):
    "maps xlim of ax2 to x1 and x2 in ax1"
    (x1, _), (x2, _) = ax2.transData.inverted().transform(ax1.transData.transform([[x1, 0], [x2, 0]]))
    xs, xe = ax2.get_xlim()
    k, b = np.polyfit([x1, x2], [xs, xe], 1)
    ax2.set_xlim(xs*k+b, xe*k+b)

align_xaxis(ax2, ax1, 0, n-1)

以下是完整代码:

{{1}}

和输出:

enter image description here