如何使用轴标签作为列标题在每个子图下方显示表格

时间:2019-04-07 21:59:14

标签: python pandas matplotlib

我试图在图中的两个子图的每一个下显示一个数据表,这些图是我使用pandas的plot函数绘制的。我已经有了所需的图,可以让两个表之一显示在两个子图之一的下面,但这是不可读的(而且我只想显示两个图之一)。

我的目标是使每个图表和表格看起来像这样:https://matplotlib.org/gallery/misc/table_demo.html#sphx-glr-gallery-misc-table-demo-py,其中轴充当列标题,数据直接位于每个图表下方。不幸的是,我的身材不是那样出来的。下面是我的代码,如果运行该代码,则应生成我所看到的内容。

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

# Set up df
rowcol = {'ID':[101,101,101,101], 'Assessment': ['Read-Write-1','Math-1', 'Read-Write-Math-3', 'Read-Write-Math-4'],
          'Math': [np.nan,4,3,3], 'MScore': [np.nan, 636.5, 577.2, 545.4],
          'RW': [3, np.nan, 3, 3], 'RWScore': [559.7, np.nan, 621.6, 563.7]}
df = pd.DataFrame(data = rowcol)
df = df.interpolate()

# Set up subplots
fig, axes = plt.subplots(nrows=1, ncols=2, sharex=True)
df.plot(x='Assessment', y=['MScore', 'RWScore'], use_index = True, 
        grid = True, style=['+r-.', 'xb--'], legend=['MScore','RWScore'], 
        ax=axes[0], xticks=[0,1,2,3])
df.plot(x='Assessment', y=['Math', 'RW'], use_index = True, 
        grid = True, style=['+g-.', 'xc--'], legend=['M','RW'], 
        xticks=[0,1,2,3], ylim=[0,4], yticks=[1,2,3,4], ax=axes[1])

# Add labels, titles, and legend
axes[0].set_title(df['ID'][0])
axes[1].set_title(df['ID'][0])
plt.xlabel('Assessment')
axes[0].set_ylabel('Score')
axes[1].set_ylabel('Performance Level')
plt.legend(loc='best')

# Add data tables
table1 = plt.table(cellText = [df.MScore, df.RWScore],
                   rowLabels = ['MScore', 'RWScore'],
                   rowColours = ['r','b'], loc='bottom',
                   colLabels = df['Assessment'])
table2 = plt.table(cellText = [df.Math, df.RW],
                   rowLabels = ['Math', 'RW'],
                   rowColours = ['g','c'], loc='bottom',
                   colLabels = df['Assessment'])

# Show plot
plt.show()

如您所见,这不会产生特别漂亮甚至可读的内容。要使此代码像链接中的示例一样工作,需要对其进行哪些更改?

1 个答案:

答案 0 :(得分:1)

  

要使该代码像链接中的示例一样工作,需要对其进行哪些更改?

示例中的数据集与问题中的数据集有很大不同。此外,还涉及两个子图和表格。出于可读性考虑,您可以更改代码以增加图形大小,为表格腾出空间,在每个子图下方显示表格,隐藏xtick标签和x轴标签。

rowcol = {'ID':[101,101,101,101], 'Assessment': ['Read-Write-1','Math-1', 'Read-Write-Math-3', 'Read-Write-Math-4'],
          'Math': [np.nan,4,3,3], 'MScore': [np.nan, 636.5, 577.2, 545.4],
          'RW': [3, np.nan, 3, 3], 'RWScore': [559.7, np.nan, 621.6, 563.7]}
df = pd.DataFrame(data = rowcol)
df = df.interpolate()
# print(df)
# Set up subplots
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(30, 10)) #specify size of subplots
df.plot(x='Assessment', y=['MScore', 'RWScore'], use_index = True, 
        grid = True, style=['+r-.', 'xb--'], legend=['MScore','RWScore'], 
        ax=axes[0], xticks=[0,1,2,3])
df.plot(x='Assessment', y=['Math', 'RW'], use_index = True, 
        grid = True, style=['+g-.', 'xc--'], legend=['M','RW'], 
        xticks=[0,1,2,3], ylim=[0,4], yticks=[1,2,3,4], ax=axes[1])


# Add labels, titles, and legend
plt.subplots_adjust(left=0.3, bottom=0.2, wspace = 0.3)
axes[0].set_title(df['ID'][0])
axes[1].set_title(df['ID'][0])
axes[0].set_ylabel('Score')
axes[1].set_ylabel('Performance Level')
#set visibility of x-axis and y-axis, xticklabels and yticklabels
axes[0].xaxis.set_ticklabels([])
axes[1].xaxis.set_ticklabels([])
axes[0].get_xaxis().set_visible(False)
axes[1].get_xaxis().set_visible(False)
plt.legend(loc='best')


# Add data tables for each subplot
table1 = axes[0].table(cellText = [df.MScore, df.RWScore],
                   rowLabels = ['MScore', 'RWScore'],
                   rowColours = ['r','b'], loc='bottom',
                   colLabels = df['Assessment'])
table2 = axes[1].table(cellText = [df.Math, df.RW],
                   rowLabels = ['Math', 'RW'],
                   rowColours = ['g','c'], loc='bottom',
                   colLabels = df['Assessment'], fontsize=15)

# Show plot
plt.show()

输出

enter image description here