[英]How To Add Color to Specific Range of Table Columns in Matplotlib
I'm attempting to add a colormap to a matplotlib table.我正在尝试将颜色图添加到 matplotlib 表中。 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'
).当所有数据都是整数时,我可以成功地这样做,但我目前有一列是导致程序失败的所有文本(
TypeError: '<' not supported between instances of 'int' and 'str'
)。 How would I skip the STRINGS
column when applying my colormap?应用颜色图时如何跳过
STRINGS
列?
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()
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.我所做的是复制
df
,在一个没有数字会达到的值中添加白色,然后将'STRINGS'
列中的所有值设为该值。
# 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))
)
I would set the STRING
column as the index of the dataframe, and then set the rowlabels
paramater to df.index
:我会将
STRING
列设置为数据框的索引,然后将rowlabels
参数设置为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:输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.