我有一个相关矩阵帽,我试图用matplotlib可视化。我可以很好地创建一个热图样式图,但我遇到了我想要标签的问题。我甚至不确定这是否可行,但这是我尝试做的事情,似乎无法使其发挥作用:
我的相关矩阵是150 X 150.在x或y(或两者都是......这并不重要)轴上,我想对标签进行分组,然后只需用颜色标记它们,或者在彩色背景上的白色标签。
为了澄清,让我们说我想要1-15作为"第1组"或者只是一个蓝色的酒吧,或者"第1组"蓝色条上的文本。那么16-20为"第2组"在红色的酒吧,或简单的红色酒吧。等等,通过矩阵中的所有项目。
我在对轴标签进行分组以及获取任何颜色方面都失败了。任何帮助将不胜感激。我的代码如下,虽然它非常基础,但我不知道它是否会有所帮助。
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
# COREELATION MATRIX TEST #
corr = np.genfromtxt(csv_path,delimiter=',')
fig = plt.figure()
ax1 = fig.add_subplot(111)
cmap = cm.get_cmap('jet', 30)
cax = ax1.imshow(corr, cmap=cmap)
ax1.grid(True)
plt.title('THIS IS MY TITLE')
fig.colorbar(cax, ticks=[-1,-0.8,-0.6,-0.4,-0.2,0.0,0.2,0.4,0.6,0.8,1.0])
plt.show()
答案 0 :(得分:2)
您可以在绘图旁边创建辅助轴,并绘制彩色条形图。关闭轴刺使这些条看起来像标签盒。
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
# COREELATION MATRIX TEST #
corr = 2*np.random.rand(150,150)-1
# labels [start,end]
labels = np.array([[0,15],[16,36],[37,82],[83,111],[112,149]])
colors = ["crimson", "limegreen","gold","orchid","turquoise"]
fig, ax = plt.subplots()
im = ax.imshow(corr, cmap="Blues")
ax.set_title('THIS IS MY TITLE')
fig.colorbar(im, ticks=[-1,-0.8,-0.6,-0.4,-0.2,0.0,0.2,0.4,0.6,0.8,1.0])
# create axes next to plot
divider = make_axes_locatable(ax)
axb = divider.append_axes("bottom", "10%", pad=0.06, sharex=ax)
axl = divider.append_axes("left", "10%", pad=0.06, sharey=ax)
axb.invert_yaxis()
axl.invert_xaxis()
axb.axis("off")
axl.axis("off")
# plot colored bar plots to the axes
barkw = dict( color=colors, linewidth=0.72, ec="k", clip_on=False, align='edge',)
axb.bar(labels[:,0],np.ones(len(labels)),
width=np.diff(labels, axis=1).flatten(), **barkw)
axl.barh(labels[:,0],np.ones(len(labels)),
height=np.diff(labels, axis=1).flatten(), **barkw)
# set margins to zero again
ax.margins(0)
ax.tick_params(axis="both", bottom=0, left=0, labelbottom=0,labelleft=0)
# Label the boxes
textkw = dict(ha="center", va="center", fontsize="small")
for k,l in labels:
axb.text((k+l)/2.,0.5, "{}-{}".format(k,l), **textkw)
axl.text(0.5,(k+l)/2., "{}-{}".format(k,l), rotation=-90,**textkw)
plt.show()