我在网上找了很长时间,但不知道怎么做。我需要绘制几个 xticks 定义为 numpy.arange(1,N) 的图形,每个图形的 N 都不同。我希望 xticks 之间的间距在所有图形上都相同(例如 1 厘米),也就是说,每个图形的宽度必须取决于 numpy.arange(1,N) 的大小。知道怎么做吗?
问问题
1256 次
2 回答
2
我认为您可以通过仔细控制轴大小(作为图形的一部分)ax.set_xlim
和fig.set_size_inches
(doc)来设置图形的实际大小来做到这一点。
前任
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.set_xlim([0,N])
fig.set_size_inches([N/2.54,h])
于 2012-08-22T18:46:10.177 回答
1
为了扩展@tcaswell 的答案,当我想对轴的真实尺寸和刻度间距离的实际尺寸进行微观管理时,我就是这样做的。
import numpy as np
import matplotlib.pyplot as plt
plt.close('all')
#------------------------------------------------------ define xticks setup ----
xticks_pos = np.arange(11) # xticks relative position in xaxis
N = np.max(xticks_pos) - np.min(xticks_pos) # numbers of space between ticks
dx = 1 / 2.54 # fixed space between xticks in inches
xaxis_length = N * dx
#------------------------------------------------------------ create figure ----
#---- define margins size in inches ----
left_margin = 0.5
right_margin = 0.2
bottom_margin = 0.5
top_margin = 0.25
#--- calculate total figure size in inches ----
fwidth = left_margin + right_margin + xaxis_length
fheight = 3
fig = plt.figure(figsize=(fwidth, fheight))
fig.patch.set_facecolor('white')
#---------------------------------------------------------------- create axe----
#---- axes relative size ----
axw = 1 - (left_margin + right_margin) / fwidth
axh = 1 - (bottom_margin + top_margin) / fheight
x0 = left_margin / fwidth
y0 = bottom_margin / fheight
ax0 = fig.add_axes([x0, y0, axw, axh], frameon=True)
#---------------------------------------------------------------- set xticks----
ax0.set_xticks(xticks_pos)
plt.show(block=False)
fig.savefig('axis_ticks_cm.png')
这导致一个 11.8 厘米的图形,x 轴为 10 厘米,每个刻度之间有 1 厘米的空间:
于 2015-07-30T14:12:53.100 回答