gpt4 book ai didi

python - matplotlib:更改用seaborn.heatmap绘制的ndim直方图的轴刻度

转载 作者:行者123 更新时间:2023-12-01 08:03:16 24 4
gpt4 key购买 nike

动机:

我正在尝试可视化许多 n 维向量的数据集(假设我有 10k 个向量,n=300 维)。我想做的是计算 n 个维度中每个维度的直方图,并将其绘制为 bins*n 热图中的单线。

到目前为止我已经得到了这个:

import numpy as np
import matplotlib
from matplotlib import pyplot as plt
%matplotlib inline
import seaborn as sns

# sample data:
vectors = np.random.randn(10000, 300) + np.random.randn(300)

def ndhist(vectors, bins=500):
limits = (vectors.min(), vectors.max())
hists = []
dims = vectors.shape[1]
for dim in range(dims):
h, bins = np.histogram(vectors[:, dim], bins=bins, range=limits)
hists.append(h)
hists = np.array(hists)
fig = plt.figure(figsize=(16, 9))
sns.heatmap(hists)
axes = fig.gca()
axes.set(ylabel='dimensions', xlabel='values')
print(dims)
print(limits)

ndhist(vectors)

这会生成以下输出:

300
(-6.538069472429366, 6.52159540162285)

bad axes ticks

问题/疑问:

如何更改轴刻度?

  • 对于 y 轴,我想简单地将其更改回 matplotlib 的默认值,因此它会选择像 0, 50, 100, ..., 250 这样的不错的刻度。 (299300 可获得奖励积分)
  • 对于 x 轴,我想将显示的 bin 索引转换为 bin(左)边界,然后,如上所述,我想将其更改回 matplotlib 的一些“nice”刻度的默认选择,例如-5, -2.5, 0, 2.5, 5 (还包括实际限制的奖励积分 -6.538, 6.522 )

自己的解决方案尝试:

我已经尝试过很多类似以下的事情:

def ndhist_axlabels(vectors, bins=500):
limits = (vectors.min(), vectors.max())
hists = []
dims = vectors.shape[1]
for dim in range(dims):
h, bins = np.histogram(vectors[:, dim], bins=bins, range=limits)
hists.append(h)
hists = np.array(hists)
fig = plt.figure(figsize=(16, 9))
sns.heatmap(hists, yticklabels=False, xticklabels=False)
axes = fig.gca()
axes.set(ylabel='dimensions', xlabel='values')
#plt.xticks(np.linspace(*limits, len(bins)), bins)
plt.xticks(range(len(bins)), bins)
axes.xaxis.set_major_locator(matplotlib.ticker.AutoLocator())
plt.yticks(range(dims+1), range(dims+1))
axes.yaxis.set_major_locator(matplotlib.ticker.AutoLocator())
print(dims)
print(limits)

ndhist_axlabels(vectors)

even worse axes ticks

但是,正如您所看到的,轴标签非常错误。我的猜测是,范围或限制存储在原始轴中的某个位置,但在切换回 AutoLocator 时丢失了。 。非常感谢您朝正确的方向插入。

最佳答案

也许你想太多了。要绘制图像数据,可以使用 imshow 并免费获取刻度和格式。

import numpy as np
from matplotlib import pyplot as plt

# sample data:
vectors = np.random.randn(10000, 300) + np.random.randn(300)

def ndhist(vectors, bins=500):
limits = (vectors.min(), vectors.max())
hists = []
dims = vectors.shape[1]

for dim in range(dims):
h, _ = np.histogram(vectors[:, dim], bins=bins, range=limits)
hists.append(h)
hists = np.array(hists)

fig, ax = plt.subplots(figsize=(16, 9))

extent = [limits[0], limits[-1], hists.shape[0]-0.5, -0.5]
im = ax.imshow(hists, extent=extent, aspect="auto")
fig.colorbar(im)

ax.set(ylabel='dimensions', xlabel='values')

ndhist(vectors)
plt.show()

enter image description here

关于python - matplotlib:更改用seaborn.heatmap绘制的ndim直方图的轴刻度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55646883/

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