📜  如何使用 Matplotlib 创建表格?

📅  最后修改于: 2022-05-13 01:54:30.779000             🧑  作者: Mango

如何使用 Matplotlib 创建表格?

在本文中,我们将讨论如何在Python中使用 Matplotlib 创建表。

方法一:使用 matplotlib.plyplot.table()函数创建表格

在这个例子中,我们创建了一个连续 5 年科目平均分的数据库。我们连续每年导入包和情节线图。可以使用 matplotlib.pyplot.table() 将表格添加到 Axes。我们可以通过在 x 轴和 y 轴上取值来绘制表格。

句法

Python3
# importing packages and modules
import numpy as np
import matplotlib.pyplot as plt
  
# average marks data for 5 consecutive years
data = [[98, 95,  93, 96,  97],
        [97, 92,  95, 94,  96],
        [98, 95,  93, 95,  94],
        [96, 94,  94, 92,  95],
        [95, 90,  91, 94,  98]]
  
columns = ('English', 'Maths', 'Physics',
           'Chemistry', 'Biology')
rows = ['%d academic year' % x for x in (2015, 2016, 2017, 2018, 2019)]
  
# Get some pastel shades for the colors
colors = plt.cm.BuPu(np.linspace(0, 0.5, len(rows)))
n_rows = len(data)
  
index = np.arange(len(columns)) + 0.3
bar_width = 0.4
  
# Initialize the vertical-offset for
# the line plots.
y_offset = np.zeros(len(columns))
  
# Plot line plots and create text labels 
# for the table
cell_text = []
for row in range(n_rows):
    plt.plot(index, data[row], color=colors[row])
    y_offset = data[row]
    cell_text.append([x for x in y_offset])
  
# Reverse colors and text labels to display
# the last value at the top.
colors = colors[::-1]
cell_text.reverse()
  
# Add a table at the bottom of the axes
the_table = plt.table(cellText=cell_text,
                      rowLabels=rows,
                      rowColours=colors,
                      colLabels=columns,
                      loc='bottom')
  
# Adjust layout to make room for the table:
plt.subplots_adjust(left=0.2, bottom=0.2)
  
plt.ylabel("marks".format(value_increment))
plt.xticks([])
plt.title('average marks in each consecutive year')
  
plt.show()


Python3
# import packages and modules
import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from pandas.plotting import table
  
# loading the iris dataset
iris = load_iris()
  
# creating a 2 dimensional dataframe out of the given data
iris_df = pd.DataFrame(data=np.c_[iris['data'],
                                  iris['target']], 
                       columns=iris['feature_names'] + ['target'])
  
# grouping data and calculating average
grouped_dataframe = iris_df.groupby('target').mean().round(1)
grouped_dataframe['species_name'] = ['setosa', 'versicolor', 'virginica']
  
# plotting data
ax = plt.subplot(211)
plt.title("Iris Dataset Average by Plant Type")
plt.ylabel('Centimeters (cm)')
  
ticks = [4, 8, 12, 16]
a = [x - 1 for x in ticks]
b = [x + 1 for x in ticks]
  
plt.xticks([])
  
plt.bar(a, grouped_dataframe.loc[0].values.tolist()[
        :-1], width=1, label='setosa')
plt.bar(ticks, grouped_dataframe.loc[1].values.tolist()[
        :-1], width=1, label='versicolor')
plt.bar(b, grouped_dataframe.loc[2].values.tolist()[
        :-1], width=1, label='virginica')
  
plt.legend()
plt.figure(figsize=(12, 8))
table(ax, grouped_dataframe.drop(['species_name'], axis=1), loc='bottom')


输出:

方法 2:使用 pandas.plotting.table() 方法创建表

代码从导入包开始,我们从 sklearn.datasets 加载 iris 数据集,下一步是将数据分组以形成二维数据集。之后,我们为每个物种绘制条形图并使用 pandas.plotting.table() 方法创建一个表格。

Python3

# import packages and modules
import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from pandas.plotting import table
  
# loading the iris dataset
iris = load_iris()
  
# creating a 2 dimensional dataframe out of the given data
iris_df = pd.DataFrame(data=np.c_[iris['data'],
                                  iris['target']], 
                       columns=iris['feature_names'] + ['target'])
  
# grouping data and calculating average
grouped_dataframe = iris_df.groupby('target').mean().round(1)
grouped_dataframe['species_name'] = ['setosa', 'versicolor', 'virginica']
  
# plotting data
ax = plt.subplot(211)
plt.title("Iris Dataset Average by Plant Type")
plt.ylabel('Centimeters (cm)')
  
ticks = [4, 8, 12, 16]
a = [x - 1 for x in ticks]
b = [x + 1 for x in ticks]
  
plt.xticks([])
  
plt.bar(a, grouped_dataframe.loc[0].values.tolist()[
        :-1], width=1, label='setosa')
plt.bar(ticks, grouped_dataframe.loc[1].values.tolist()[
        :-1], width=1, label='versicolor')
plt.bar(b, grouped_dataframe.loc[2].values.tolist()[
        :-1], width=1, label='virginica')
  
plt.legend()
plt.figure(figsize=(12, 8))
table(ax, grouped_dataframe.drop(['species_name'], axis=1), loc='bottom')

输出:

分组数据框如下所示:

情节如下: