【问题标题】:Custom ticks for seaborn heatmapseaborn 热图的自定义刻度
【发布时间】:2018-11-11 11:18:32
【问题描述】:

我有一些data 想绘制为热图,它本质上是一个 50x50 的 numpy 数组。结果,热图轴标签的范围从 0 到 50,但实际上我希望轴标签从 -114 到 114,因为这是数据的范围。但是,当我设置刻度标签时,它们最终会聚集在轴上(见图)。

当我输入线时

ax.set_xticks(ticks)
ax.set_yticks(ticks)

热图最终被缩放(见图)。

我已经输入了我的代码和一些示例数据,也许有人能发现我做错了什么。

import sys
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import os
import cv2 as cv
import seaborn as sns;

filepath = sys.argv[1]
drive, path_and_file = os.path.splitdrive(filepath)
path, file = os.path.split(path_and_file)

line_width = 3

font = {'family' : 'sans',
        'weight' : 'normal',
        'size'   : 18}
matplotlib.rc('font', **font)

bagnames = ["hex_events_only.bag"]
groundtruth = [-92, 0]
noise_levels = ["-1.000000"]
rewards = ["sos"]

gt_angle = np.arctan2(groundtruth[0], groundtruth[1])
gt_mag = np.linalg.norm(groundtruth, axis=0)
print(gt_angle, gt_mag)

for bagname in bagnames:
    print "==========", bagname, "=========="
    for reward in rewards:
        print "      ---", reward, "---       "
        for noise_level in noise_levels:
                filename = filepath + "data_field_" + bagname + "_" + reward + "_" + noise_level
                print filename
                n_samples = (pd.read_csv(filename, delimiter="\t", skiprows=1, names=["vx", "vy", "measure"])).values

                x = n_samples[:, 0]
                y = n_samples[:, 1]
                z = n_samples[:, 2]

                yrange = int(np.ptp(x))
                xrange = int(np.ptp(y))

                x_values = np.unique(x).size
                y_values = np.unique(y).size

                num_ticks = 10
                ticks = np.linspace(int(-yrange/2.), int(yrange/2.), num_ticks, dtype=np.int)

                img = np.reshape(z, (x_values, y_values))
                img = img.T
                img = cv.resize(img, (yrange, xrange))

                savename = filepath + "hmap_" + bagname + "_" + reward + "_" + noise_level

                fig, ax = plt.subplots()

                img = cv.GaussianBlur(img, (5, 5), 0)
                ax = sns.heatmap(img, cmap='viridis', yticklabels=ticks, xticklabels=ticks)

                # ax.set_xticks(ticks)
                # ax.set_yticks(ticks)

                # ax.axvline(groundtruth[0], linestyle='--', c='r', linewidth=line_width)
                # ax.axhline(groundtruth[1], linestyle='--', c='r', linewidth=line_width)
                plt.show()
                fig.savefig(savename + ".png", transparent=True, bbox_inches='tight', pad_inches=0)
                plt.close()

https://1drv.ms/u/s!Ap0up1KFhZOughZ3dx9rwq-9yiF9

【问题讨论】:

  • 您不想在此处使用sns.heatmap。取决于网格是在您想要plt.imshowplt.pcolormesh 绘图的中心还是边缘上定义的。
  • @ImportanceOfBeingErnest 为什么?
  • 因为它根本不打算用于此目的。 searborn.heatmap 在内部使用 pcolormesh 并以有助于显示分类图的方式对其进行操作。在这里,您没有分类图。因此,直接使用pcolormesh 绘图(或实际上是imshow,取决于所需的网格)要容易得多,而不是在外部尝试恢复heatmap 在内部对此所做的所有更改。

标签: python matplotlib seaborn heatmap


【解决方案1】:

@ImportanceOfBeingErnest 向我指出,使用 Seaborn 的方法首先是错误的(参见 cmets)。所以我改变了方法,现在它完全按照我的意愿工作。万一其他人遇到这个问题,下面的代码会根据数据生成热图:

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

font = {'family' : 'sans',
        'weight' : 'normal',
        'size'   : 18}
matplotlib.rc('font', **font)

filepath = "path/to/data/"
dataname = "data.txt"
filename = filepath + dataname

n_samples = (pd.read_csv(filename, delimiter="\t", skiprows=1, names=["x", "y", "value"])).values

x = n_samples[:, 0]
y = n_samples[:, 1]
z = n_samples[:, 2]

line_width = 2

yrange = int(np.ptp(x))
xrange = int(np.ptp(y))

x_values = np.unique(x).size
y_values = np.unique(y).size

num_ticks = 10
ticks = np.linspace(int(-yrange/2.), int(yrange/2.), num_ticks, dtype=np.int)

img = np.reshape(z, (x_values, y_values))
img = img.T
img = cv.resize(img, (yrange, xrange))

fig, ax = plt.subplots()
im = ax.imshow(img, cmap='viridis', extent=[-xrange/2., xrange/2., -yrange/2., yrange/2.])
ax.axvline(groundtruth[0], linestyle='--', c='r', linewidth=line_width)
ax.axhline(groundtruth[1], linestyle='--', c='r', linewidth=line_width)
ax.set_xlabel("$v_x$")
ax.set_ylabel("$v_y$")
cbar = fig.colorbar(im)
cbar.ax.set_yticklabels([''])
cbar.ax.set_ylabel('Reward')

fig.tight_layout()
savename = filepath + "hmap_" + bagname + "_" + reward + "_" + noise_level
fig.savefig(savename + ".pdf", transparent=True, bbox_inches='tight', pad_inches=0)
plt.close()
# plt.show()

输出如下:

【讨论】:

    猜你喜欢
    • 2018-05-26
    • 2017-04-05
    • 2020-04-19
    • 1970-01-01
    • 2016-01-14
    • 2016-03-29
    • 2021-05-08
    • 2020-10-21
    相关资源
    最近更新 更多