简体   繁体   English

我可以将 Seaborn 图叠加到 Matplotlib 图上吗?

[英]Can I overlay a Seaborn plot onto a Matplotlib graph?

I have a function that produces a matplotlib map.我有一个生成 matplotlib 地图的函数。 I then want to overlay a seaborn heat map on top of this map, and have both maps exactly the same size on top of each other, while being able to see the details of both maps.然后,我想在这张地图上叠加一张 seaborn 热图,并让两张地图彼此重叠的大小完全相同,同时能够看到两张地图的详细信息。 Is it possible?是否可以? Please see my code below.请在下面查看我的代码。

def draw_map():
    fig=plt.figure()
    fig.set_size_inches(14.5, 8.8)
    ax=fig.add_subplot(1,1,1)
    
    #Map Outline & Centre Line
    plt.plot([0,0],[0,88], color="black")
    plt.plot([0,145],[88,88], color="black")
    plt.plot([145,145],[88,0], color="black")
    plt.plot([145,0],[0,0], color="black")

    ly97 = [39,49] 
    lx97 = [72.5,72.5]
    plt.plot(lx97,ly97,color="black")
    
    seaborn.heatmap(data)
    plt.ylim(0, 88)
    plt.xlim(0, 145)
                    
    #Display Map
    plt.show()
    

For some reason the seaborn heatmap appears tiny in comparison to the matplotlib map.出于某种原因,与 matplotlib 地图相比,seaborn 热图显得很小。 The data in the seaborn heatmap contains values between 0 and 1 only, if this helps.如果有帮助的话,seaborn 热图中的数据仅包含 0 到 1 之间的值。 Thanks in advance.提前致谢。

When drawing an MxN array as a heatmap, seaborn creates it with an x-dimension from 0 to N-1 and a y-dimension from 0 to M-1 .MxN数组绘制为热图时,seaborn 使用从0N-1的 x 维度和从0M-1的 y 维度创建它。 There doesn't seem to be a way to provide your own dimensions.似乎没有办法提供您自己的尺寸。 As seaborn calls matplotlib's pcolormesh() to draw the heatmap, you can call it directly.由于seaborn调用matplotlib的pcolormesh()来绘制热图,所以可以直接调用。 pcolormesh() does accept parameters to set the x and y dimensions. pcolormesh()接受参数来设置 x 和 y 维度。

The example below uses the standard "object-oriented" interface for pyplot.下面的示例使用 pyplot 的标准“面向对象”接口 Alpha and green lines are used, to get some more contrast between the lines and the heatmap with seaborn's default colormap.使用 Alpha 和绿线,通过 seaborn 的默认颜色图在线条和热图之间获得更多对比度。

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

fig, ax = plt.subplots(figsize=(14.5, 8.8))

# Map Outline & Centre Line
ax.plot([0, 0], [0, 88], color="lime", lw=3)
ax.plot([0, 145], [88, 88], color="lime", lw=3)
ax.plot([145, 145], [88, 0], color="lime", lw=3)
ax.plot([145, 0], [0, 0], color="lime", lw=3)

ly97 = [39, 49]
lx97 = [72.5, 72.5]
ax.plot(lx97, ly97, color="lime", lw=3)

M = 20
N = 30
data = np.random.rand(M, N)
# sns.heatmap(data)
ax.pcolormesh(np.linspace(0, 145, N+1), np.linspace(0, 88, M+1), data, alpha=0.4,
              cmap=sns.color_palette("rocket", as_cmap=True))
# ax.set_ylim(0, 88)
# ax.set_xlim(0, 145)

plt.show()

示例图

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

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