gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:13:04 24 4
gpt4 key购买 nike

虽然我可以在一个图表上获得多条线和一个图表上的多个条形图 - 但我无法使用相同的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com