gpt4 book ai didi

python - 将注释框添加到 matplotlib 等高线/热图图

转载 作者:行者123 更新时间:2023-11-28 20:48:21 28 4
gpt4 key购买 nike

我想生成一个带有颜色条的等高线图/热图,然后添加一个注释框。这个数字很丑,但得到了我想要的:

example image

add_subplot() 是不够的。如果我尝试将所有内容都放在同一个子图中,则该框会被遮盖。我可以通过使其可拖动然后调整图像的大小来解决这个问题,但这并不好。我将不得不制作一些这样的图像,所有这些图像都是标准尺寸的,我不能一次又一次地与尺寸抗争。

我也尝试了 axes(),将盒子放在一个单独的轴上。但这会生成一个新的绘图窗口,覆盖了我的大部分颜色条。我想会有办法让窗口完全透明。但是到了那个地步,我想我的做法一定是完全错误的。

这似乎不应该那么难。有什么想法吗?

最佳答案

等高线图的注释框:

much better graph

这样做:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
from numpy.random import randn

from mpl_toolkits.axes_grid1.axes_divider import HBoxDivider
import mpl_toolkits.axes_grid1.axes_size as Size


def make_heights_equal(fig, rect, ax1, ax2, ax3, pad):
# pad in inches

h1, v1 = Size.AxesX(ax1), Size.AxesY(ax1)
h2, v2 = Size.AxesX(ax2, 0.1), Size.AxesY(ax2)
h3, v3 = Size.AxesX(ax3), Size.AxesY(ax3)

pad_v = Size.Scaled(1)
pad_h = Size.Fixed(pad)

my_divider = HBoxDivider(fig, rect,
horizontal=[h1, pad_h, h2, pad_h, h3],
vertical=[v1, pad_v, v2, pad_v, v3])


ax1.set_axes_locator(my_divider.new_locator(0))
ax2.set_axes_locator(my_divider.new_locator(2))
ax3.set_axes_locator(my_divider.new_locator(4))


# Make plot with vertical (default) colorbar
fig = plt.figure()
img_ax = fig.add_subplot(131)
bar_ax = fig.add_subplot(132)
ann_ax = fig.add_subplot(133)

data = np.clip(randn(250, 250), -1, 1)

im = img_ax.imshow(data, interpolation='nearest', cmap=cm.coolwarm)

# Add colorbar, make sure to specify tick locations to match desired ticklabels
cbar = fig.colorbar(im, cax=bar_ax, ticks=[-1, 0, 1])
cbar.ax.set_yticklabels(['< -1', '0', '> 1'])# vertically oriented colorbar

ann_ax.axis('off')

ann_ax.annotate("Hello, I'm an annotation", (0.5, 0.5),
xycoords="axes fraction", va="center", ha="center",
bbox=dict(boxstyle="round, pad=1", fc="w"))

make_heights_equal(fig, 111, img_ax, bar_ax, ann_ax, 0.2)

plt.savefig("try.png")

关于python - 将注释框添加到 matplotlib 等高线/热图图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17072716/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com