【问题标题】:Plot on top of seaborn clustermap在 seaborn clustermap 上绘制
【发布时间】:2015-12-28 09:02:45
【问题描述】:

我使用seaborn.clustermap 生成了一个集群图。 我想在热图顶部绘制/绘制一条水平线,如下图

我只是尝试将 matplotlib 用作:

plt.plot([x1, x2], [y1, y2], 'k-', lw = 10)

但该行不显示。 seaborn.clustermap 返回的对象没有类似question 中的任何属性。 如何绘制线?

这是生成类似于我发布的“随机”集群图的代码:

import numpy as np
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import random 

data = np.random.random((50, 50))
df = pd.DataFrame(data)
row_colors = ["b" if random.random() > 0.2 else "r"  for i in range (0,50)]
cmap = sns.diverging_palette(133, 10, n=7, as_cmap=True)
result = sns.clustermap(df, row_colors=row_colors, col_cluster = False, cmap=cmap, linewidths = 0)
plt.plot([5, 30], [5, 5], 'k-', lw = 10)
plt.show()

【问题讨论】:

  • 您能否提供一个生成集群图的最小工作示例,以便我们可以使用它?我本来希望您的代码能够正常工作,但是您正在绘制的线可能卡在了集群图后面?也许您可以使用 plt.plot( ... , zorder=10) 设置线条的 z 顺序。
  • 我尝试使用 plt.plot( ... , zorder=10) 但没有任何改变。我添加了一个工作示例。
  • clustermap 图有多个轴,plt.plot 在“活动”轴上绘制,但这可能不是热图轴。所以你只需要在相关轴上调用 plot 方法,这将是你调用的对象的属性result

标签: python pandas matplotlib plot seaborn


【解决方案1】:

您想要的坐标区对象隐藏在 ClusterGrid.ax_heatmap 中。此代码找到该轴并简单地使用 ax.plot() 来绘制线。您也可以使用 ax.axhline()。

import numpy as np
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import random 

data = np.random.random((50, 50))
df = pd.DataFrame(data)
row_colors = ["b" if random.random() > 0.2 else "r"  for i in range (0,50)]
cmap = sns.diverging_palette(133, 10, n=7, as_cmap=True)
result = sns.clustermap(df, row_colors=row_colors, col_cluster = False, cmap=cmap, linewidths = 0)
print dir(result)  # here is where you see that the ClusterGrid has several axes objects hiding in it
ax = result.ax_heatmap  # this is the important part
ax.plot([5, 30], [5, 5], 'k-', lw = 10)
plt.show()

【讨论】:

    猜你喜欢
    • 2019-01-19
    • 2016-04-06
    • 2023-01-10
    • 1970-01-01
    • 2015-03-11
    • 2020-09-01
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多