【问题标题】:Python seaborn heatmap grid - Not taking expected columnsPython seaborn热图网格 - 不采用预期的列
【发布时间】:2017-10-30 06:06:30
【问题描述】:

我有以下熊猫数据框。基本上,7个不同的动作类别,5个不同的目标,每个类别有1个或多个独特的端点,然后每个端点在每个目标中得到一定的分数。 共有 250 个端点。

action,target,endpoint,score
Category1,target1,endpoint1,813.0
Category1,target2,endpoint1,757.0
Category1,target3,endpoint1,155.0
Category1,target4,endpoint1,126.0
Category1,target5,endpoint1,75.5
Category2,target1,endpoint2,106.0
Category2,target1,endpoint3,101.0
Category2,target1,endpoint4,499.0
Category2,target1,endpoint5,207.0
Category2,target2,endpoint2,316.0
Category2,target2,endpoint3,208.0
Category2,target2,endpoint4,161.0
Category2,target2,endpoint5,198.0
<omit>
Category3,target1,endpoint8,193.0
Category3,target1,endpoint9,193.0
Category3,target1,endpoint10,193.0
Category3,target1,endpoint11,193.0
Category3,target2,endpoint8,193.0
Category3,target2,endpoint9,193.0
<List goes on...>

现在,我想将此数据框映射为每个类别的热图。 所以,我使用了带有以下代码的 seabron facet grid heatmap。

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

data = pd.read_csv('rawData.csv')
data = data.drop('Unnamed: 0', 1)


def facet_heatmap(data, **kwargs):


    data2 = data.pivot(index="target", columns='endpoint', values='score')
    ax1 = sns.heatmap(data2, cmap="YlGnBu", linewidths=2)

    for item in ax1.get_yticklabels():
        item.set_rotation(0)

    for item in ax1.get_xticklabels():
        item.set_rotation(70)


with sns.plotting_context(font_scale=5.5):

    g = sns.FacetGrid(data, col="action", col_wrap=7, size=5, aspect=0.5)

cbar_ax = g.fig.add_axes([.92, .3, .02, .4])  

g = g.map_dataframe(facet_heatmap, cbar=cbar_ax, min=0, vmax=2000)
# <-- Specify the colorbar axes and limits

g.set_titles(col_template="{col_name}", fontweight='bold', fontsize=18)
g.fig.subplots_adjust(right=3)  # <-- Add space so the colorbar doesn't overlap the plot

plt.savefig('seabornPandas.png', dpi=400)
plt.show()

它实际上会生成热图网格。但是,问题是每个热图出于某种原因使用相同的列。请参阅下面的截图。

(请忽略彩条和限制。)

这很奇怪。首先,索引不按顺序排列。其次,每个热图框只取最后三个端点(端点 248、249 和 250)。这是不正确的。对于类别 1,它应该只采用端点 1。我不希望那里有一个灰色的框..

对于category2,它应该取端点2,3,4,5。不是端点 248、249、250。

如何解决这两个问题?欢迎任何建议或cmets。

【问题讨论】:

  • 您确定data2 看起来像您认为的那样吗?
  • 听起来你需要关闭 x 轴共享,但一般来说,如果 x 因子嵌套在 col 因子内(而不是交叉),它不完全是正确的绘图结构一个分面网格。
  • @AndrasDeak 是的,我确认数据 2 看起来符合预期。每个端点都按目标显示。
  • @mwaskom 你能帮我了解如何关闭 x 轴共享吗?我只是想试试看会有什么帮助。
  • 有一个sharex参数。

标签: python-3.x matplotlib heatmap seaborn


【解决方案1】:

按照 mwaskom 的建议:使用 sharex 参数来解决您的问题:

...

with sns.plotting_context(font_scale=5.5):

g = sns.FacetGrid(data, col="action", col_wrap=7, size=5, aspect=0.5,
                 sharex=False)

...

【讨论】:

    猜你喜欢
    • 2020-08-04
    • 2018-05-15
    • 2015-09-12
    • 2017-04-16
    • 2021-04-07
    • 2021-04-11
    • 2020-10-12
    • 2016-05-02
    相关资源
    最近更新 更多