[英]matplotlib: reduce axes width in subplots
I have a matplotlib bar chart, which bars are colored according to some rules through a colormap. 我有一个matplotlib条形图,根据一些规则通过色图将条形图着色。 I need a colorbar on the right of the main axes, so I added a new axes with
我需要在主轴右侧有一个颜色条,所以我添加了一个新的轴
fig, (ax, ax_cbar) = plt.subplots(1,2)
and managed to draw my color bar in the ax_bar axes, while I have my data displayed in the ax axes. 并设法在ax_bar轴上绘制我的颜色条,同时我的数据显示在ax轴上。 Now I need to reduce the width of the ax_bar, because it looks like this:
现在我需要减小ax_bar的宽度,因为它看起来像这样:
How can I do? 我能怎么做?
Using subplots
will always divide your figure equally. 使用
subplots
将始终平均分配您的数字。 You can manually divide up your figure in a number of ways. 您可以通过多种方式手动分割图形。 My preferred method is using
subplot2grid
. 我首选的方法是使用
subplot2grid
。
In this example, we are setting the figure to have 1 row and 10 columns. 在这个例子中,我们将图设置为1行10列。 We then set
ax
to be the start at row,column = (0,0) and have a width of 9 columns. 然后我们将
ax
设置为行的开始,列=(0,0)并且宽度为9列。 Then set ax_cbar
to start at (0,9) and has by default a width of 1 column. 然后将
ax_cbar
设置为从(0,9)开始,默认情况下宽度为1列。
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8,6))
num_columns = 10
ax = plt.subplot2grid((1,num_columns), (0,0), colspan=num_columns-1)
ax_cbar = plt.subplot2grid((1,num_columns), (0,num_columns-1))
The ususal way to add a colorbar is by simply putting it next to the axes: 添加颜色条的常用方法是将其放在轴旁边:
fig.colorbar(sm)
where fig
is the figure and sm
is the scalar mappable to which the colormap refers. 其中
fig
是图形, sm
是色彩图所指的标量可映射。 In the case of the bars, you need to create this ScalarMappable
yourself. 对于条形图,您需要自己创建此
ScalarMappable
。 Apart from that there is no need for complex creation of multiple axes. 除此之外,不需要复杂的多轴创建。
import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np
fig , ax = plt.subplots()
x = [0,1,2,3]
y = np.array([34,40,38,50])*1e3
norm = matplotlib.colors.Normalize(30e3, 60e3)
ax.bar(x,y, color=plt.cm.plasma_r(norm(y)) )
ax.axhline(4.2e4, color="gray")
ax.text(0.02, 4.2e4, "42000", va='center', ha="left", bbox=dict(facecolor="w",alpha=1),
transform=ax.get_yaxis_transform())
sm = plt.cm.ScalarMappable(cmap=plt.cm.plasma_r, norm=norm)
sm.set_array([])
fig.colorbar(sm)
plt.show()
If you do want to create a special axes for the colorbar yourself, the easiest method would be to set the width already inside the call to subplots
: 如果你想自己为colorbar创建一个特殊的轴,最简单的方法是在
subplots
的调用中设置宽度:
fig , (ax, cax) = plt.subplots(ncols=2, gridspec_kw={"width_ratios" : [10,1]})
and later put the colorbar to the cax
axes, 然后将
cax
轴上,
fig.colorbar(sm, cax=cax)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.