在matplotlib imshow()图形轴上更改值 [英] Change values on matplotlib imshow() graph axis

查看:135
本文介绍了在matplotlib imshow()图形轴上更改值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一些输入数据:

data = np.random.normal(loc=100,scale=10,size=(500,1,32))
hist = np.ones((32,20)) # initialise hist
for z in range(32):
    hist[z],edges = np.histogram(data[:,0,z],bins=np.arange(80,122,2))

我可以使用imshow()绘制它:

plt.imshow(hist,cmap='Reds')

获取:

但是,x轴值与输入数据不匹配(即平均值为100,范围从80到122).因此,我想更改x轴以显示edges中的值.

However, the x-axis values do not match the input data (i.e. mean of 100, range from 80 to 122). Therefore, I'd like to change the x-axis to show the values in edges.

我尝试过:

ax = plt.gca()
ax.set_xlabel([80,122]) # range of values in edges
...
# this shifts the plot so that nothing is visible

ax.set_xticklabels(edges)
...
# this labels the axis but does not centre around the mean:

关于如何更改轴值以反映我正在使用的输入数据的任何想法?

Any ideas on how I can change the axis values to reflect the input data I am using?

推荐答案

如果可能的话,我会尽量避免更改xticklabels,否则,例如在用其他数据过度绘制直方图时,它可能会造成很大的混乱.

I would try to avoid changing the xticklabels if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data.

定义网格的范围可能是最好的,使用imshow可以通过添加extent关键字来完成.这样,轴将自动调整.如果您想更改标签,我可能会在set_xticks后面加上一些格式化程序.直接更改标签应该是最后的选择.

Defining the range of your grid is probably the best and with imshow it can be done by adding the extent keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks with perhaps some formatter. Altering the labels directly should be the last resort.

fig, ax = plt.subplots(figsize=(6,6))

ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])
ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio

这篇关于在matplotlib imshow()图形轴上更改值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆