繁体   English   中英

Pyplot 热图中的轴标签

[英]Axis Labels in Pyplot Heatmap

我可以使用以下方法制作热图:

Index= [np.arange(0, 1, 1/5)]
Cols = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=Index, columns=Cols)

plt.pcolor(df)
plt.yticks(np.arange(0.5, len(df.index),   1), df.index)
plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)
plt.show()

这使:

在此处输入图像描述

请问如何将 y 轴标签更改为“0.0 0.5 1.0”

您可以通过在对 imshow 的调用中使用关键字参数范围来 label x 和 y 轴。

extent : scalars (left, right, bottom, top), optional, default: None
Data limits for the axes.  //The default assigns zero-based row,
column indices to the `x`, `y` centers of the pixels.

作为示例,您需要使用从 pylab 导入所有数据

from pylab import *
input! = rand(5,5)
figure(1)
imshow(input1, interpolation='nearest')
grid(True)

left = 7.5
right = 9.5
bottom = 7.5
top = -0.5
extent = [left, right, bottom, top]

figure(2)
imshow(input1, interpolation='nearest', extent=extent)
grid(True)

show();

我找到了让 yticks 工作的方法

len_I = 50
Index= [np.arange(0, 1, 1/len_I)]
Cols = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(len_I, 4)), index=Index, columns=Cols)

plt.pcolor(df)
plt.yticks(np.arange(0, (len(df.index)+1), len(df.index)/2), np.arange(0, len(df.index), 0.5))
plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)
plt.show()

这给出:

在此处输入图像描述

pcolor在由 x 和 y 位置给定的网格点之间绘制彩色矩形。 您需要的行和列比值多。 您可以在 4 列的位置 0、1、2、3、4 处设置 x 网格,网格点之间的刻度位置很好。 y 轴可以是常规轴,其中MultipleLocator可以将刻度位置设置为所需的倍数。

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import numpy as np
import pandas as pd

num_rows = 600
cols = ['A', 'B', 'C', 'D']
num_cols = len(cols)
df = pd.DataFrame(abs(np.random.randn(num_rows, num_cols).cumsum(axis=0)), columns=cols)

plt.pcolor(range(num_cols+1), np.linspace(0, 1, num_rows+1), df.to_numpy(), cmap='hot')
plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)
plt.gca().yaxis.set_major_locator(MultipleLocator(0.5))
plt.show()

结果图

暂无
暂无

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

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