matplotlib matshow:如何根据缩放矢量更改每行的高度? [英] matplotlib matshow: How to change each row height based on a scaling vector?

查看:41
本文介绍了matplotlib matshow:如何根据缩放矢量更改每行的高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用标准 matshow 示例:

Using the standard matshow example:

from matplotlib.pylab import *
dim = (12,12)
aa = zeros(dim)
for i in range(min(dim)):
    aa[i,i] = i
matshow(aa)
show()


(来源:matplotlib.org)

如何控制每一行的高度?

How can I control each row's height?

在我的情况下,行索引(即国家/地区)可以用非线性间距(例如 GDP)表示以表示大小,我想通过改变缩放向量的行高来表示.(即,如果有 12 行,那么在均匀分布的情况下,每行的行高为 1/12,由 [0.083, 0.083, ...., 0.083] 表示,那么不均匀的行高可以由总和为1)

In my case the row indices (i.e countries) could be represented by non-linear spacing (such as GDP) to signify magnitude and I would like to represent that by altering the row height from a scaling vector. (i.e. If there are 12 rows then with the uniform distribution each row would have a row height of 1/12 represented by [0.083, 0.083, ...., 0.083] then uneven row heights could be set by any vector that sums to 1)

推荐答案

您可以使用pcolormesh(或pcolor)创建由多边形组成的数组,这些多边形可以具有所需的任何形状.我认为像 matshow 或 imshow 这样的普通数组绘图将始终沿轴具有恒定大小.

You can use pcolormesh (or pcolor) to create an array made of polygons, these can have any shape you want. I think normal array plotting like matshow or imshow will always have a constant size along an axis.

n = 6

# generate some data
gdp = np.array(np.random.randint(10,500,n))
countries = np.array(['Country%i' % (i+1) for i in range(n)])
matr = np.random.randint(0,10,(n,n))

# get the x and y arrays
y = np.insert(gdp.cumsum(),0,0)
xx,yy = np.meshgrid(np.arange(n+1),y)

# plot the matrix
fig, axs = plt.subplots(figsize=(6,6))

axs.pcolormesh(xx,yy,matr.T, cmap=plt.cm.Reds, edgecolors='k')

axs.set_ylim(y.min(),y.max())

# set the yticks + labels
axs.set_yticks(y[1:] - np.diff(y) / 2)
axs.set_yticklabels(countries)

#set xticks + labels
axs.xaxis.set_ticks_position('top')
axs.set_xticks(np.arange(n)+0.5)
axs.set_xticklabels(np.arange(n))

高度根据:

print countries
['Country1' 'Country2' 'Country3' 'Country4' 'Country5' 'Country6']

print gdp
[421 143 134 388 164 420]

这篇关于matplotlib matshow:如何根据缩放矢量更改每行的高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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