Aligning table to X-axis using matplotlib Python



The Python Matplotlib library allows us to create visual plots from given data. To make the data easier to read and relate to the chart, we can display it in the form of a table and position it directly below the corresponding bar chart.

Since the x-axis runs horizontally, we arrange the table in the same direction so that each value aligns correctly under its corresponding bar. Based on this concept, we demonstrate the diagram as follows:

Steps to Align a Table to the X-axis Using Matplotlib

Following are the steps to create a table and store data values below the x-axis using matplotlib:

Step 1: Import the Python NumPy and Matplotlib libraries.

import numpy as np
import matplotlib.pyplot as plt

Step 2: Set the figure size and adjust the padding between and around the subplots.

# set the width and height of the plot(inches)
plt.rcParams["figure.figsize"] = [7.00, 3.50]
# adjust padding around the subplots
plt.rcParams["figure.autolayout"] = True

Step 3: Create a list of data for the dataframe.

data = [
[66386, 174296, 75131, 577908, 32015], # 100 year
[58230, 381139, 78045, 99308, 160454], # 50 year
[89135, 80552, 152558, 497981, 603535], # 20 year
[78415, 81858, 150656, 193263, 69638], # 10 year
[139361, 331509, 343164, 781380, 52269] # 5 year
]

Step 4: Set the labels and find the above data length.

columns = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail')
rows = ['%d year' % x for x in (100, 50, 20, 10, 5)] 
# find the data length 
n_rows = len(data)     

Here,

  • Columns: We use Python tuples for column names to identify the plots.
  • rows: We use list comprehension to set row labels in a year(number) format.

Step 5: Define the range of values and visual appearance.

values = np.arange(0, 2500, 500)
value_increment = 1000
colors = plt.cm.BuPu(np.linspace(0, 0.5, len(rows)))

Here,

  • arrange(0, 2500, 500): It creates an array of values used as tick marks for the y-axis. For example, 0, 500, 1000, etc.
  • value_increment = 1000: It is a multiplier that scales tick values.
  • plt.cm.BuPu(): This is Matplotlib built-in method to set the colors in the form of blue or purple shades.

Step 6: Initialization of plotting parameters.

index = np.arange(len(columns)) + 0.3
bar_width = 0.4
y_offset = np.zeros(len(columns))
cell_text = []

Here,

  • index: This sets the positions for each group of bars along the x-axis.
  • bar_width: It is used to represent bar thickness.
  • y_offset: It is used for stacking bars.
  • cell_text: It stores table values.

Step 7: Create a Stacked Bar Chart.

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 / 1000.0) for x in y_offset])

In a stacked bar chart, stacked refers to multiple series of data that layered vertically or horizontally on top of each other within a single bar. The simple diagram of stacked bar chart:


Step 8: Adding a table below the plots.

colors = colors[::-1]
cell_text.reverse()
the_table = plt.table(
    cellText=cell_text,
    rowLabels=rows,
    rowColours=colors,
    colLabels=columns,
    loc='bottom'
)

Step 9: Adjustment of final plots, which includes layout spacing, y-axis labels, removal of X-axis ticks, and title name.

plt.subplots_adjust(left=0.2, bottom=0.2)
plt.ylabel("Loss in $1000's")
plt.yticks(values * value_increment, ['%d' % val for val in values])
plt.xticks([])
plt.title('Loss by Disaster')
Step 10: Show the plot.
plt.show()

Code to Align a Table to the X-axis Using Matplotlib

Here is the complete Python program demonstrating all the above steps to align a table with the X-axis using Matplotlib:

# libraries required
import numpy as np
import matplotlib.pyplot as plt

# set the width and height of the plot(inches)
plt.rcParams["figure.figsize"] = [7.00, 3.50]
# adjust padding around the subplots
plt.rcParams["figure.autolayout"] = True

# custom data
data = [
[66386, 174296, 75131, 577908, 32015], # 100 year
[58230, 381139, 78045, 99308, 160454], # 50 year
[89135, 80552, 152558, 497981, 603535], # 20 year
[78415, 81858, 150656, 193263, 69638], # 10 year
[139361, 331509, 343164, 781380, 52269] # 5 year
]

columns = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail')
rows = ['%d year' % x for x in (100, 50, 20, 10, 5)] 
# find the data length 
n_rows = len(data)       

# range of value and visual appearance
values = np.arange(0, 2500, 500)
value_increment = 1000
colors = plt.cm.BuPu(np.linspace(0, 0.5, len(rows)))

# create stacked bar chart
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 / 1000.0) for x in y_offset])

# Display the table below the X-axis line
colors = colors[::-1]
cell_text.reverse()
the_table = plt.table(
    cellText=cell_text,
    rowLabels=rows,
    rowColours=colors,
    colLabels=columns,
    loc='bottom'
)

# Set the final plots
plt.subplots_adjust(left=0.2, bottom=0.2)
plt.ylabel("Loss in $1000's")
plt.yticks(values * value_increment, ['%d' % val for val in values])
plt.xticks([])
plt.title('Loss by Disaster')

# Show the plots
plt.show()

The above code produces the following result:


Conclusion

While aligning a table with the x-axis, we need to use the Python libraries, NumPy and Matplotlib for numerical calculations and data visualization, respectively. To position the table below the x-axis, we perform several operations such as preparing the data list, creating labels, customizing visual appearance, adjusting plotting parameters, etc.

Updated on: 2025-07-11T17:35:10+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements