import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
data = {' A ': [0, 0, 0.012, 0, 0, 0, 0],
' B ': [0.1, 0, 0.035, 0.12, 0, 0, 0],
' C ': [0, 0, 0, 0, 0.5, 0, 0.2],
' D ': [0, 0.23, 0, 0, 0, 0, 0.33],
' E ': [0, 0.1, 0, 0.6, 0.9, 0.2, 0],
' F ': [0, 0, 0.78, 0, 0, 0, 0.31],
' G ': [0, 0.15, 0, 0, 0, 0.4, 0]}
df = pd.DataFrame(data)
columns = df.columns
# These are the same values than 'columns'
rows = [r for r in columns]
# Get some pastel shades for the colors
colors = plt.cm.BuPu(np.linspace(0, 0.5, len(rows)))
print(colors)
# Plot bars and create text labels for the table
cell_text = []
# Take a look that data is extracted from the Pandas df
for row in df.to_numpy():
cell_text.append([x for x in row])
# Reverse colors and text labels to display the last value at the top.
colors = colors[::-1]
# Add a table at the bottom of the Axes
the_table = plt.table(cellText=cell_text,
rowLabels=rows,
rowColours=colors,
colLabels=columns,
colColours=colors,
loc='center')
the_table.scale(2, 2)
plt.title('Some Data Matrix')
plt.axis('off')
# If you want to save the table to disk...
plt.savefig('/some/local/directory/table_matrix.png', bbox_inches='tight')
# If you want to show the matrix table in a REPL capable of rendering...
plt.show()
Last active
January 13, 2025 19:45
-
-
Save yordanoweb/01e27b2e760e469bb99da363f8001310 to your computer and use it in GitHub Desktop.
Create a PNG table image from a Pandas Dataframe
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment