Matplotlib Table in Python With Examples

Hello programmers, today, we will learn about the implementation of Matplotlib tables in Python. The matplotlib.pyplot.table() method is used to create or add a table to axes in python programs. It generates a table used as an extension to a stacked bar chart. Before we move on with various examples and formatting of tables, let me just brief you about the syntax and return type of the Matplotlib table function.

Matplotlib Table in Python is a particular function that allows you to plot a table. So far, there are multiple plotting techniques such as aggregate bars, aggregate line charts, and other ways. By using matplotlib.pyplot.table(), we can add a table to Axes. This table is then plotted with columns as an x-axis and values as the y-axis. Let’s have a look at the syntax and full explanation of code –

Syntax of Matplotlib Table:

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)

Specifying one of cellText or cellColours as a parameter to the matplotlib table function is mandatory. These parameters must be 2D lists, in which the outer lists define the rows and the inner list define the column values of each row. Any other dimensional data will not be accepted by the function.

The table can optionally have row and column headers. rowLabels, rowColours, rowLoc, and colLabels, colColours, colLoc respectively are optional parameters for the function. **kwargs are optional parameters to adjust for the size of the 2-d list passed as a parameter.

Parameters:

  • cellText: The texts to place into the table cells.
  • cellColours: The background colors of the cells.
  • cellLoc: The alignment of the text within the cells. (default: ‘right’)
  • colWidths (optional)The column widths in units of the axes.
  • rowLabels (optional)The text of the row header cells.
  • rowColours (optional)The colors of the row header cells.
  • rowLoc (optional): The text alignment of the row header cells. (default: ‘left’)
  • colLabels (optional): The text of the column header cells.
  • colColours (optional): The colors of the column header cells.
  • colLoc (optional): The text alignment of the column header cells.(default: ‘left’)
  • Loc (optional)This parameter is the position of the cell with respect to ax.
  • bbox (optional)This parameter is the bounding box to draw the table into.
  • edges (optional): This parameter is the cell edges to be drawn with a line.
  • **kwargs: Used to control table properties.

Return type :

The matplotlib.pylot.table() method returns the table created passing the required data as parameters. This table object can be grabbed to change the specific values within the table. This object refers to the matplotlib.table.Table() object. The table consists of 2d grid that can be index by using rows and columns. Moreover, you can also change the font family of the table.

Implementation of Matplotlib table

import matplotlib.pyplot as plt 
  
val1 = ["{:X}".format(i) for i in range(10)] 
val2 = ["{:02X}".format(10 * i) for i in range(10)] 
val3 = [["" for c in range(10)] for r in range(10)] 
  
fig, ax = plt.subplots() 
ax.set_axis_off() 
table = ax.table( 
    cellText = val3,  
    rowLabels = val2,  
    colLabels = val1, 
    rowColours =["palegreen"] * 10,  
    colColours =["palegreen"] * 10, 
    cellLoc ='center',  
    loc ='upper left')         
  
ax.set_title('matplotlib.axes.Axes.table() function Example', 
             fontweight ="bold") 
  
plt.show() 

Output:

Implementation of Matplotlib table

Explanation:

In the above example, matplotlib.pyplot.table() accepts the 2-d list as the parameter. The parameters passed are as follows:- cellText = val3, rowLabels = val2, colLabels = val1, rowColours =[“palegreen”] * 10, colColours =[“palegreen”] * 10, cellLoc =’center’, loc =’upper left’. Val1, val2 and val3 runs for loops each to generate values for column lables, row lables and cell text, respectively. Setting rowColours and colColours to ‘palegreen’ changes the color of row and column header cells to palegreen. Setting cellLoc =’center’ sets the alignment of header row and column values to center. And finally, loc =’upper left’ sets the alignment of the Title to upper left.

Style Row and Column Headers

rcolors = plt.cm.BuPu(np.full(len(row_headers), 0.1))
ccolors = plt.cm.BuPu(np.full(len(column_headers), 0.1))

the_table = plt.table(cellText=cell_text,
                      rowLabels=row_headers,
                      rowColours=rcolors,
                      rowLoc='right',
                      colColours=ccolors,
                      colLabels=column_headers,
                      loc='center')

Output:

Style Row and Column Headers

Explanation:

The above code snippet is used to style row and column headers.lists of colors, one for every row header cell and another for every column header cell. Row header horizontal alignment is set to right. We’ll just use the plt.cm.BuPm color map to fill two lists of colors, one for every row header cell and another for every column header cell. There are better choices than a linear color map for decorative colors though.

Styling the Matplotlib Table in Python

fig_background_color = 'skyblue'
fig_border = 'steelblue'

plt.figure(linewidth=2,
           edgecolor=fig_border,
           facecolor=fig_background_color
          )

plt.savefig('pyplot-table-figure-style.png',
            bbox_inches='tight',
            edgecolor=fig.get_edgecolor(),
            facecolor=fig.get_facecolor(),
            dpi=150
            )

Output:

Styling the Matplotlib Table in Python

Explanation:

We can explicitly declare the figure to get easy control of its border and background color. In the above code snippet,Sky blue is the background color and the figure border is set to steel blue.

Full Matplotlib Table Example As Bar Graph

In the following example, we’ll use the data of mobile phone usage in 2010, 2012, 2014, and 2016 years. The table have rows of Make Calls, Take Photos, Texting, Internet and Playing Games. From the following trend, you can infer that the usage of mobile phones is increasing year by year. We’ll use matplotlob.pyplot.Table() to create a table object and show it using the Tkinter window.

import numpy as np
import matplotlib.pyplot as plt


data = [[ 100, 100,  99, 95],
        [ 66, 71,  76,  82],
        [ 73,  75, 79, 81],
        [ 17,  23, 42, 55],
        [ 12, 18, 26, 20]]

columns = ('2010', '2012', '2014', '2016')
rows = ("Make Calls", "Take Photos", "Texting", "Internet", "Playing games")[::-1]

values = np.arange(0, 50, 10)
value_increment = 10

# 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 stacked bar chart.
y_offset = np.zeros(len(columns))

# Plot bars and create text labels for the table
cell_text = []
for row in range(n_rows):
    plt.bar(index, data[row], bar_width, bottom=y_offset, color=colors[row])
    y_offset = y_offset + data[row]
    cell_text.append(['%1.1f' % (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("Usage of mobile phones in ${0}'s".format(value_increment))
plt.yticks(values * value_increment, ['%d' % val for val in values])
plt.xticks([])
plt.title('Using Mobile Phones')

plt.show()

Output –

Using Mobile Phones

Explanation –

First, we import all the necessary modules and then declare the datasets in the form of 2d list. Next, we create a table object by passing appropriate parameters. Then we finally use plt.show() to display the matplotlib interface.

Full Matplotlib Table Example As Line Graph

In the previous example, we plotted a bar graph for the given dataset of mobile phones. In this example, we’ll plot a line graph for every row of the dataset to check its trend. Line graphs are better to get an idea of trends in a dataset. We’ll use the basic matplotlib.plot() to plot every row as a line. Let’s jump on to the code –

import numpy as np
import matplotlib.pyplot as plt

data = [[ 100, 100,  99, 95],
        [ 66, 71,  76,  82],
        [ 73,  75, 79, 81],
        [ 17,  23, 42, 55],
        [ 12, 18, 26, 20]]

columns = ('2010', '2012', '2014', '2016')
rows = ("Make Calls", "Take Photos", "Texting", "Internet", "Playing games")[::-1]

values = np.arange(0, 10, 1)
value_increment = 10

# Get some pastel shades for the colors
colors = plt.cm.BuPu(np.linspace(0, 0.5, len(rows)))
colors = colors[::-1]
index = np.arange(len(columns)) + 0.3
bar_width = 0.4
n_rows = len(data)

for row in range(n_rows):
    plt.plot(index, data[row], bar_width, color=colors[row])

plt.table(cellText=data, rowLabels=rows, rowColours=colors, colLabels=columns, loc='bottom')

plt.subplots_adjust(left=0.25, bottom=0.25)
plt.ylabel("Usage of mobile phones in ${0}'s".format(value_increment))
plt.yticks(values * value_increment, ['%d' % val for val in values])
plt.xticks([])
plt.title('Using Mobile Phones')

plt.show()

Output –

Full Matplotlib Table Example

Explanation –

The explanation is similar to the previous one. The only change in the code was using plt.plot() instead of plt.bar(). This created a line graph of all rows in the Tkinter window.

Full Matplotlib Table Example As Pie Charts

Pie charts are a unique way of display of data. This section will learn about creating Pie Charts for a 2-d table and using them. All the pie charts generated are used to create the matplotlib grid axes. This grid automatically adjusts to the size of pie charts.

import numpy as np
import matplotlib.pyplot as plt

data = [[ 100, 100,  99, 95],
        [ 66, 71,  76,  82],
        [ 73,  75, 79, 81],
        [ 17,  23, 42, 55],
        [ 12, 18, 26, 20]]
data = list(map(list, zip(*data)))
columns = ('2010', '2012', '2014', '2016')
rows = ("Make Calls", "Take Photos", "Texting", "Internet", "Playing games")[::-1]

fig, axs = plt.subplots(2, 2)
axs[0, 0].pie(data[0], labels=rows, autopct='%1.1f%%', shadow=True)
axs[0, 0].set_title(columns[0])
axs[0, 1].pie(data[1], labels=rows, autopct='%1.1f%%', shadow=True)
axs[0, 1].set_title(columns[1])
axs[1, 0].pie(data[2], labels=rows, autopct='%1.1f%%', shadow=True)
axs[1, 0].set_title(columns[2])
axs[1, 1].pie(data[3], labels=rows, autopct='%1.1f%%', shadow=True)
axs[1, 1].set_title(columns[3])

plt.show()

Output –

Full Matplotlib Table Example As Pie Charts

Explanation –

Firstly, we created axes using plt.subplots(). This function returns a specific workspace where you can plot the charts individually. Then we can use either loop through those points or plot each pie independently. In this case, I’ve manually added each pie in individual axes.

Conclusion

This article brings to you very simple and brief concepts of Matplotlib tables in python. It includes ways of inserting tables in your python program in a very neat manner. Methods to style the table and row and column headers are so explicitly discussed here. Refer to this article for any queries related to tables.

However, if you have any doubts or questions do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

Subscribe
Notify of
guest
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Jet
Jet
2 years ago

I do lots of programming in several programming languages. I have taken 3 courses in Python and I tutor programming. This webpage had helpful info and ideas for some graphics I’m creating.

Pratik Kinage
Admin
2 years ago
Reply to  Jet

Thank you for your encouraging words.

Regards,
Pratik

efueyo
efueyo
1 year ago

Dear all. How can we modify the height of the cells in each row? Regards