【问题标题】:matplotlib correlation matrix heatmap with grouped colors as labelsmatplotlib 相关矩阵热图,以分组颜色作为标签
【发布时间】:2017-09-30 22:08:37
【问题描述】:

我有一个相关矩阵帽,我正在尝试使用 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()

【问题讨论】:

  • 输入数据看起来如何,分组参数是什么?请提供带有一些示例数据的minimal reproducible example,并使用它来解释绘图的外观。可能你想要的一个简单的绘图也可以帮助理解所需的情节。
  • 我在网上找到了一张图片,显示了类似的数据以及我想做的事情:[link]researchgate.net/profile/Deanna_Greene/publication/292707637/…) 在这个例子中他们有红线和标签(例如“默认模式”和“视觉的”)。我想以相同的方式对我的变量进行分组,但不是矩阵中的红线,我宁愿标签只是一个颜色样本。类似于侧面的颜色条,但需要手动设置颜色。

标签: python-2.7 matplotlib heatmap correlation axis-labels


【解决方案1】:

您可以在绘图旁边创建辅助轴并为其绘制彩色条形图。关闭轴刺让这些条看起来像标签框。

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()

【讨论】:

    猜你喜欢
    • 2019-07-22
    • 2016-04-21
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 2022-12-11
    相关资源
    最近更新 更多