Home > other >  How To Add Color to Specific Range of Table Columns in Matplotlib
How To Add Color to Specific Range of Table Columns in Matplotlib

Time:07-11

I'm attempting to add a colormap to a matplotlib table. I can do so, successfully, when all the data is intergers, but I currently have a column that's all text which is causing the program to fail(TypeError: '<' not supported between instances of 'int' and 'str' ). How would I skip the STRINGS column when applying my colormap?

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import colors
from matplotlib.colors import ListedColormap

# define figure and axes
fig, ax = plt.subplots()

# hide the axes
fig.patch.set_visible(False)
ax.axis('off')
ax.axis('tight')

# create data
df = pd.DataFrame({
    'STRINGS': ['STRING1', 'STRING2', 'STRING3', 'STRINGS4', 'STRINGS5'],
    'Success Rate 1': [95, .02, -.03, 92, .05],
    'Success Rate 2': [-95, .06, .03, 92, .05]
})

#Colors
red_green = ListedColormap(['red', '#70e000', '#38b000'])
bounds = [-20, 0, 1, 100]
norm = colors.BoundaryNorm(bounds, red_green.N)

# create table
matplotlib_table = plt.table(
    cellText=df.values,
    colLabels=df.columns,
    loc='center',
    cellColours=red_green(norm(df.values))
)

# display table
fig.tight_layout()
plt.show()

enter image description here

CodePudding user response:

What I did was to make a copy of df, add white in a value that no number is going to reach, and then make all the values in 'STRINGS' column to be that value.

# Colors
red_green = ListedColormap(['white', 'red', 'red', '#70e000', '#38b000'])
bounds = [-1000, -999, -20, 0, 1, 100]
norm = colors.BoundaryNorm(bounds, red_green.N)

temp_df = df.copy()
temp_df['STRINGS'] = -1000
# create table
matplotlib_table = plt.table(
    cellText=df.values,
    colLabels=df.columns,
    loc='center',
    cellColours=red_green(norm(temp_df.values))
)

CodePudding user response:

I would set the STRING column as the index of the dataframe, and then set the rowlabels paramater to df.index:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import colors
from matplotlib.colors import ListedColormap

# define figure and axes
fig, ax = plt.subplots()

# hide the axes
fig.patch.set_visible(False)
ax.axis('off')
ax.axis('tight')

# create data
df = pd.DataFrame({
    'STRINGS': ['STRING1', 'STRING2', 'STRING3', 'STRINGS4', 'STRINGS5'],
    'Success Rate 1': [95, .02, -.03, 92, .05],
    'Success Rate 2': [-95, .06, .03, 92, .05]
})

#Colors
red_green = ListedColormap(['red', '#70e000', '#38b000'])
bounds = [-20, 0, 1, 100]
norm = colors.BoundaryNorm(bounds, red_green.N)

df = df.set_index('STRINGS')

matplotlib_table = plt.table(
    cellText=df.values,
    colLabels=df.columns,
    rowLabels=df.index,
    loc='center',
    cellColours=red_green(df.values),
)

# display table
fig.tight_layout()
plt.show()

Output:

enter image description here

  • Related