【问题标题】:Heatmap as background of a Plot in matplotlib热图作为 matplotlib 中绘图的背景
【发布时间】:2019-02-27 10:26:38
【问题描述】:

我有以下情节:

已使用此代码生成:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

ttc = pd.read_excel("../XLSX_Files/Baseline_Data.xlsx", sheet_name="Data")["TTC"]
risks = col.OrderedDict(
[("very low", 0), ("low", 0), ("medium-to-low", 0), ("medium", 0), ("high-to-medium", 0), ("high", 0),
 ("very high", 0)])

---- Part in which risks get filled --- 

for x in risks:
     risk_distribution.append(float(risks[x]) / len(ttc))

x = np.arange(1, len(risks) + 1)
y = np.arange(0.0, 0.4, 0.05)
xticks = risks.keys()
fig, ax = plt.subplots()
plt.plot(x, risk_distribution)
ax.set_ylim(0, 0.4)
plt.show()

所以我的实际问题是:如何添加风险热图作为背景(与此相同:https://www.latestquality.com/risk-heat-map/

到目前为止我所做的尝试:

import seaborn as sns
risk_heatmap = [
    [1.2, 0.7, 0.7, 0.3, 0, 0, 0],
    [1.2, 0.7, 0.7, 0.7, 0.5, 0, 0],
    [1.2, 1.2, 1.2, 0.7, 0.7, 0, 0],
    [2.0, 1.2, 1.2, 1.2, 0.7, 0.7, 0],
    [2.0, 2.0, 2.0, 1.2, 1.2, 0.7, 0.7]
 ]

ax = sns.heatmap(risk_heatmap, linewidth=0.5, cbar=False, cmap="RdYlGn")

但这给了我一些看起来很奇怪的图表。

有没有一种方法可以在不丢失 y 维度的情况下添加热图?

【问题讨论】:

    标签: python python-2.7 matplotlib plot heatmap


    【解决方案1】:

    您遇到的问题是 y 比例不一定会匹配。您需要覆盖共享相同 x 轴的 2 个轴。您可以使用matplotlib.axes.Axes.twinx 来完成此操作。

    import matplotlib.pyplot as plt
    import seaborn as sns
    risk_heatmap = [
        [1.2, 0.7, 0.7, 0.3, 0, 0, 0],
        [1.2, 0.7, 0.7, 0.7, 0.5, 0, 0],
        [1.2, 1.2, 1.2, 0.7, 0.7, 0, 0],
        [2.0, 1.2, 1.2, 1.2, 0.7, 0.7, 0],
        [2.0, 2.0, 2.0, 1.2, 1.2, 0.7, 0.7]
     ]
    
    ax1 = sns.heatmap(risk_heatmap, linewidth=0.5, cbar=False, cmap="RdYlGn")
    
    ax2 = ax1.twinx()
    ax2.plot(np.random.random(7) * .3)
    ax2.set_ylim(0, 0.4)
    
    plt.show()
    

    这是另一个example

    【讨论】:

      猜你喜欢
      • 2021-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多