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

标签 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()

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

最佳答案

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

最难的是如何对齐x轴刻度。这里我们定义了align函数,它将ax2.get_xlim()[0]ax1ax2.get_xlim中的x1对齐()[1]ax1 中的 x2:

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)

和输出:

enter image description here

关于python - 使用 DataFrame.Plot 在同一图形上绘制多个图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24227650/

相关文章:

python - 如何在 Seaborn FacetGrid 中制作正方形热图

python - 如何用pandas统计组元素的个数

python - 在 pandas 数据框中获取特定值

python - 如何像我们在 pyspark withColumn 中那样在 pandas 中动态创建新列

python - 在删除附加列的同时旋转 Pandas 数据框

python - 在这种情况下, “pre-image”是什么意思?

python - 如何在 Python 中放置图像?

python - 在 Jupyter Notebook 中使用 pyplot.scatter() 会导致 Jupyter Notebook 菜单出现错误

python-3.x - 模块 'matplotlib' 没有属性 'colors'

python - 替换 NumPy 数组中两个给定值之间的值