The Wayback Machine - https://web.archive.org/web/20240926162354/https://www.geeksforgeeks.org/how-to-create-a-table-with-matplotlib/
Open In App

How to Create a Table with Matplotlib?

Last Updated : 27 Jan, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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)

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()


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.

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')


Output:

The grouped dataframe looks as:

The plot looks as:



Similar Reads

Matplotlib.axes.Axes.table() in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. matplotlib.axes.Axes.table() Function The Axes.tab
3 min read
Matplotlib.pyplot.table() function in Python
Matplotlib.pyplot.table() is a subpart of matplotlib library in which a table is generated using the plotted graph for analysis. This method makes analysis easier and more efficient as tables give a precise detail than graphs. The matplotlib.pyplot.table creates tables that often hang beneath stacked bar charts to provide readers insight into the d
3 min read
Display the Pandas DataFrame in table style and border around the table and not around the rows
Let us see how to style a Pandas DataFrame such that it has a border around the table. We will be using the set_table_styles() method of the Styler class in the Pandas module. set_table_styles() Syntax : set_table_styles(self, table_styles) Parameters : table_styles : List, each individual table_style should be a dictionary with selector and props
1 min read
Create a pseudocolor plot of an unstructured triangular grid in Python using Matplotlib
Matplotlib is a Python module which can be used for data visualization; and analyse the data graphically in the form of pie-chart, histogram, bar graph and many more. It also has an ability to generate MATLAB-like frameworks. Unstructured triangular grid An unstructured triangular grid contains n_points points and n_tri triangles which can either b
5 min read
How to Create an Empty Figure with Matplotlib in Python?
Creating a figure explicitly is an object-oriented style of interfacing with matplotlib. The figure is a basic building block of creating a plot as Matplotlib graphs our data on figures. This figure keeps track of all other components such as child axes, legends, title, axis, etc. Steps to create an empty figure : First, we import the matplotlib li
2 min read
How to Create a Single Legend for All Subplots in Matplotlib?
The subplot() function in matplotlib helps to create a grid of subplots within a single figure. In a figure, subplots are created and ordered row-wise from the top left. A legend in the Matplotlib library basically describes the graph elements. The legend() can be customized and adjusted anywhere inside or outside the graph by placing it at various
3 min read
Create a cumulative histogram in Matplotlib
The histogram is a graphical representation of data. We can represent any kind of numeric data in histogram format. In this article, We are going to see how to create a cumulative histogram in Matplotlib Cumulative frequency: Cumulative frequency analysis is the analysis of the frequency of occurrence of values. It is the total of a frequency and a
2 min read
Create a grouped bar plot in Matplotlib
In this article, we will learn how to Create a grouped bar plot in Matplotlib. Let's discuss some concepts : Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack. It had been introduce
2 min read
Create a stacked bar plot in Matplotlib
In this article, we will learn how to Create a stacked bar plot in Matplotlib. Let's discuss some concepts: Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack.A bar plot or bar graph
3 min read
How to Create Different Subplot Sizes in Matplotlib?
In this article, we will learn different ways to create subplots of different sizes using Matplotlib. It provides 3 different methods using which we can create different subplots of different sizes. Methods available to create subplot: Gridspecgridspec_kwsubplot2gridCreate Different Subplot Sizes in Matplotlib using Gridspec The GridSpec from the g
4 min read
Create lollipop charts with Pandas and Matplotlib
In this article, we will create Lollipop Charts. They are nothing but a variation of the bar chart in which the thick bar is replaced with just a line and a dot-like “o” (o-shaped) at the end. Lollipop Charts are preferred when there are lots of data to be represented that can form a cluster when represented in the form of bars. LINK TO CSV FILE :
4 min read
Create Multiple Buttons in Matplotlib
We all very well know that Python offers us a very beautiful library named Matplotlib that has the support of numerous methods using which we can plot graphs and visualize our data. Many a time, we all want our plots to look appealing and become interactive at the same time. For that purpose, buttons can be added in our matplotlib plots that can be
4 min read
Create an Animated GIF Using Python Matplotlib
In this article, we will discuss how to create an animated GIF using Matplotlib in Python. Matplotlib can be used to create mathematics-based animations only. These can include a point moving on the circumference of the circle or a sine or cosine wave which are just like sound waves. In Matplotlib we have a library named animation from which we can
3 min read
How to Create a Candlestick Chart in Matplotlib?
A candlestick chart, often known as a Japanese candlestick chart, is a financial chart that shows the price movement of stocks, derivatives, and other financial instruments in real-time, there are simply four essential components that must be examined. The open, high, low, and close are the four key elements, the candlestick chart has been used. It
4 min read
How to Create Boxplots by Group in Matplotlib?
Boxplots by groups can be created using the matplotlib package, but, however, if you wish to make more customizations to your grouped box plot, then the seaborn package provides a go-to function that supports a wide variety of customizations to the grouped box plots. Matplotlib doesn't provide an explicit function to create a grouped box plot. We h
5 min read
Create Scatter Charts in Matplotlib using Flask
In this article, we will see how to create charts in Matplotlib with Flask. We will discuss two different ways how we can create Matplotlib charts in Flask and present it on an HTML webpage with or without saving the plot using Python. File structure Create and Save the Plot in the Static Directory Here, We first created a get_plot() function which
4 min read
How to Create Subplots in Matplotlib with Python?
In this article, we will learn how to add markers to a Graph Plot using Matplotlib with Python. For that one must be familiar with the following concepts:  Matplotlib: Matplotlib may be a multi-platform data visualization library built on NumPy arrays designed to figure with the broader SciPy stack. Matplotlib Subplots: The matplotlib.pyplot.subplo
5 min read
How to create a Scatter Plot with several colors in Matplotlib?
Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc. In this article, we will see how to create a scatter plot with differen
3 min read
How to Create Multiple Subplots in Matplotlib in Python?
To create multiple plots use matplotlib.pyplot.subplots method which returns the figure along with the objects Axes object or array of Axes object. nrows, ncols attributes of subplots() method determine the number of rows and columns of the subplot grid. By default, it returns a figure with a single plot. For each axes object i.e. plot we can set a
3 min read
How to Create a Swarm Plot with Matplotlib
Swarm plots, also known as beeswarm plots, are a type of categorical scatter plot used to visualize the distribution of data points in a dataset. Unlike traditional scatter plots, swarm plots arrange data points so that they do not overlap, providing a clear view of the distribution and density of data points across different categories. This makes
5 min read
Create a SQL table from Pandas dataframe using SQLAlchemy
In this article, we will discuss how to create a SQL table from Pandas dataframe using SQLAlchemy. As the first steps establish a connection with your existing database, using the create_engine() function of SQLAlchemy. Syntax: from sqlalchemy import create_engine engine = create_engine(dialect+driver://username:password@host:port/database) Explana
3 min read
Python: MySQL Create Table
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command.Installation Follow the below-men
3 min read
Create Table Using Tkinter
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task
3 min read
How to Create a Pivot table with multiple indexes from an excel sheet using Pandas in Python?
The term Pivot Table can be defined as the Pandas function used to create a spreadsheet-style pivot table as a DataFrame. It can be created using the pivot_table() method. Syntax: pandas.pivot_table(data, index=None) Parameters: data : DataFrame index: column, Grouper, array, or list of the previous index: It is the feature that allows you to group
2 min read
Python SQLite - Create Table
In this article, we will discuss how can we create tables in the SQLite database from the Python program using the sqlite3 module. In SQLite database we use the following syntax to create a table: CREATE TABLE database_name.table_name( column1 datatype PRIMARY KEY(one or more columns), column2 datatype, column3 datatype, ..... columnN datatype ); N
1 min read
How to Create a Pivot Table in Python using Pandas?
A pivot table is a statistical table that summarizes a substantial table like a big dataset. It is part of data processing. This summary in pivot tables may include mean, median, sum, or other statistical terms. Pivot tables are originally associated with MS Excel but we can create a pivot table in Pandas using Python using the Pandas Dataframe piv
3 min read
How to Create Delta Table in Databricks Using PySpark
An open-source storage layer called Delta Lake gives data lakes scalability, performance, and dependability. It offers a transactional layer on top of cloud storage and lets you handle massive volumes of data in a data lake. This post will explain how to use PySpark to generate a Delta table in Databricks. Delta Lake is designed to address common i
4 min read
PostgreSQL - Create table using Python
Creating tables in a PostgreSQL database using Python is a common task for developers working with databases. This process involves defining the structure of your data and ensuring that your database is optimized for efficient storage and retrieval. In this article, we will walk through the steps of creating tables in PostgreSQL using Python. Prere
3 min read
wxPython - Create Radio Button using Create() function
Create() function is used for the two-step construction of Radio Button in wxPython. Create() function takes different attributes of radio button as an argument Syntax: wx.RadioButton.Create(parent, id=ID_ANY, label="", pos=DefaultPosition, size=DefaultSize, style=0, validator=DefaultValidator, name=RadioButtonNameStr ) Parameters: ParameterInput T
1 min read
wxPython - Create Static Box using Create() method
In this article we are going to learn about Static Box in wxPython. A static box is a rectangle drawn around other windows to denote a logical grouping of items. In this article we will create Static Box using two step creation, in order to do that we will use Create() method. Syntax: wx.StaticBox.Create(parent, id=ID_ANY, label="", pos=DefaultPosi
2 min read
Article Tags :
Practice Tags :