繁体   English   中英

热图作为matplotlib中图的背景

[英]Heatmap as background of a Plot in matplotlib

我有以下情节:

图1

使用以下代码生成的代码:

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维度的情况下添加热图的方法?

您遇到的问题是y刻度不一定会匹配。 您需要叠加2个共享相同x轴的轴。 您可以使用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()

这是另一个例子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM