Matplotlib错误?表格绘图不一致

时间:2015-12-17 19:26:00

标签: python database matplotlib plot

此代码:

%matplotlib inline

import pandas as pd
import matplotlib.pyplot as plt

dc = pd.DataFrame({'A' : [1, 2, 3, 4],'B' : [4, 3, 2, 1],'C' : [3, 4, 2, 2]})

plt.plot(dc)
plt.legend(dc.columns)
plt.tight_layout()

dcsummary = pd.DataFrame([dc.mean(), dc.sum()],index=['Mean','Total'])

plt.table(cellText=dcsummary.values,colWidths = [0.25]*len(dc.columns),
        rowLabels=dcsummary.index,
        colLabels=dcsummary.columns,
        cellLoc = 'center', rowLoc = 'center',
        loc='top')
fig = plt.gcf()

#plt.show()

得到的结果如下(See/verify it here):

result1

但是,如果我禁用内联绘图并启用plt.show(),结果将会是这样的:

result2

即,如果禁用内联绘图,表格将从图表中截止。由于这是我所做的唯一改变,我认为这是matplotlib的一个错误,它无法产生一致的结果。

希望这可以在将来的版本中修复。同时,我现在如何修复它(假设我的真实表是使用pd.read_sql从数据库中提取的,并且其行数可能会不时变化)? PS,在给出解决方案时,请确保在添加图表标题时它仍然有效。感谢。

更新:更多研究表明问题与plt.tight_layout()无关。以下是我编译在一起但没有plt.tight_layout()的一个示例,但是当图表内联绘图被禁用时inline plotting is still fine除了标题和表格之外,表格也没有正确显示相互碰撞:

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt
plt.style.use('ggplot')

n=6
df = pd.DataFrame({
        'person':[x*16 for x in list('ABCDEF')],
        'score1':np.random.randn(n),
        'score2':np.random.randn(n),
        'score3':np.random.randn(n),
        'score4':np.random.randn(n),
        'score5':np.random.randn(n)
                   })
print(df)


plt.close('all')  # close all open figures

fig, ax = plt.subplots()

# X: pd.options.display.mpl_style = 'default' # cause system freeze
df.set_index(['person']).plot(kind='barh', ax = ax, width=0.85, fontsize=8)
ax.invert_yaxis()

plt.title("Matplotlib table plotting")

#plt.tight_layout()

# Add a table
plt.table(cellText=df.values,colWidths = [0.25]*len(df.columns),
        rowLabels=df.index,
        colLabels=df.columns,
        cellLoc = 'center', rowLoc = 'center',
        loc='top')

plt.show()

问题仍然存在,如何修复上述图表?

由于

0 个答案:

没有答案