[英]Change color of heatmap labels in Python (matplotlib)
I am looking to change the color of the ticklabels
in my heatmap based on some condition.我希望根据某些条件更改热图中ticklabels
的颜色。 For example below, I would like to change the colors of ticklabels
containing A
as red
and B
as green
.例如下面,我想更改包含A
为red
和B
为green
的ticklabels
的颜色。
I tried making a list ['red', 'green', 'red', 'green']
and pass it along the color option but no success so far.我尝试制作一个列表['red', 'green', 'red', 'green']
并将其传递给 color 选项,但到目前为止没有成功。 Any help would be great.任何帮助都会很棒。
import numpy as np
import matplotlib.pyplot as plt
alpha = ['ABC', 'BDF', 'ADF', 'BCF']
data = np.random.random((4,4))
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(data, interpolation='nearest')
fig.colorbar(cax)
ax.set_xticklabels(['']+alpha)
ax.set_yticklabels(['']+alpha)
plt.show()
You can set the text colour using set_color
on the label text objects:您可以在标签文本对象上使用set_color
设置文本颜色:
for l in ax.xaxis.get_ticklabels()+ax.yaxis.get_ticklabels():
if 'A' in l.get_text():
l.set_color('r')
elif 'B' in l.get_text():
l.set_color('g')
Of course, this doesn't address what happens if both A
and B
are present in the label (ie should ABC
be red or green)?当然,这并没有解决如果标签中同时存在A
和B
会发生什么情况(即ABC
应该是红色还是绿色)?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.