In this article, we will discuss how to create a table with Matplotlib in Python.
Method 1: Create a Table using matplotlib.plyplot.table() function
In this example, we create a database of average scores of subjects for 5 consecutive years. We import packages and plotline plots for each consecutive year. A table can be added to Axes using matplotlib.pyplot.table(). We can plot the table by taking columns on the x-axis and the y-axis for values.
Syntax
matplotlib.pyplot.table(cellText=None, cellColours=None, cellLoc=’right’, colWidths=None, rowLabels=None, rowColours=None, rowLoc=’left’, colLabels=None, colColours=None, colLoc=’center’, loc=’bottom’, bbox=None, edges=’closed’, **kwargs)
# 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() |
Output:
Method 2: Create a Table using pandas.plotting.table() method
The code starts with importing packages, we load the iris dataset from sklearn.datasets, next step is grouping data to form a 2-d dataset. after that, we plot bar plots for each species and create a table using the pandas.plotting.table() method.
# 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' )
|
Output:
The grouped dataframe looks as:
The plot looks as: