【问题标题】:Matplotlib table and chart overwrites next chartMatplotlib 表格和图表覆盖下一个图表
【发布时间】:2016-02-25 19:14:57
【问题描述】:

我从这个问题开始chart and table,解决方案确实将表格放在图表下方。

但是,问题的第二部分是在同一个(打印的)页面上使用多个图表。从上一个问题中提取答案并添加另一个子图表明该表覆盖了以下图表。

tight_layout 没有帮助(实际上使情况变得更糟)。

我确实尝试过保留一行(因此总行数是 3,首先从 0 开始,然后从 2 开始),但这留下了一个很大的丑陋空白,因为表格甚至没有接近填满一整行。

GridSpec 似乎也没有帮助,或者至少我不知道如何让它解决这个问题。

months = [1,2,3,4,5,6,7,8,9,10,11,12]

by_year = [
(2012,  (8,6,8,9,1,2,8,9,4,3,2,6)),
(2013,  (5,6,2,9,6,2,8,9,4,3,2,6)),
(2014,  (7,6,3,9,4,2,8,9,4,3,2,6)),
]

colors = ['r','g','b','y']
import pylab as plt
fig = plt.figure()
ax = plt.subplot2grid((2,1), (0,0))
ax2 = plt.subplot2grid((2,1), (1,0))

#0.9  to leave a small space between groups of bars
import numpy as NP
N = 0.95 / (len(by_year))

cell_text = []
for i, (year, row) in enumerate(by_year):
    print i, year, row
    idx = NP.arange(0, len(months)) + N * i
    # * 0.8 to put a small gap between bars
    ax.bar(idx, row, color=colors[i], width=N * 0.8, label=year)
    cell_text.append(row)

tbl = ax.table(cellText=cell_text, rowLabels=[x[0] for x in by_year], loc='bottom', colLabels=months)
prop = tbl.properties()
ax.set_xticks([])
lgd = ax.legend(loc='upper left', bbox_to_anchor=(1, 1.0))
fig.show()

【问题讨论】:

    标签: python matplotlib charts axis-labels


    【解决方案1】:

    好吧,我解决了这个问题。解决方案有两个部分,都涉及使用 get 和 set position。

    第一部分是在创建子图之后添加以下内容

    current_bbox = ax.get_position()
    current_bbox.y0 = .45
    ax.set_position(current_bbox)
    

    该代码将很好地移动底部。原来的 y0 是 0.3629,我不得不玩弄这些数字才能把它弄好。我无法以编程方式做到这一点(或者至少我不理解这些关系)。但是通过眼球和反复试验,价值是有效的。

    该修复会导致表格现在折叠起来,以使表格中的每一行都靠得太近。表创建时的以下代码修复了(添加 bbox)

    tbl = ax.table(cellText=cell_text, 
       rowLabels=[x[0] for x in by_year], loc='bottom', 
       bbox[0, -0.2, 1, 0.175],
       colLabels=months)
    

    数字再次被锁定到位。我敢肯定,在某个时间点,有人可以添加如何计算这些数字,而无需进行眼球调整。

    结果现在看起来像这样

    【讨论】:

      猜你喜欢
      • 2021-01-19
      • 2016-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-30
      • 2012-06-05
      • 1970-01-01
      相关资源
      最近更新 更多