首页 > 解决方案 > pandas.DataFrame.plot 创建具有双轴和不均匀索引的不正确图

问题描述

请考虑以下脚本生成的两个图。线图的位置不正确fig2

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

np.random.seed(0x5eed)

arr1 = np.random.randint(5, 10, 4)
arr2 = np.random.randint(15, 20, 4)
idx = [1, 3, 4, 5]
kwargs = {'marker': 'o', 'color': 'C1'}

fig1, ax11 = plt.subplots()
ax12 = ax11.twinx()
ax11.bar(idx, arr1)
ax12.plot(idx, arr2, **kwargs)
fig1.savefig('fig1.png')

df = pd.DataFrame({'foo': arr1, 'bar': arr2}, index=idx)
fig2, ax21 = plt.subplots()
ax22 = ax21.twinx()
df['foo'].plot.bar(ax=ax21)
df['bar'].plot.line(ax=ax22, **kwargs)
fig2.savefig('fig2.png')

fig1(预期的):

图。1

fig2(意外):

图2

经过一番调查,我发现以下条件可以重现此问题。

我发现了一个类似的问题,但对我来说不是这样。df.index是一流的Int64Index。这是预期的行为还是我应该向问题跟踪器报告的事情?

标签: pythonpandasmatplotlib

解决方案


推荐阅读