Python, Matplotlib: 带有任意数量垂直图形的字幕
Python, Matplotlib: Suptitle with arbitrary number of vertical figures
我有一个网站可以生成(取决于可用的数据站 运行)任意数量的图(作为图像),它们相互垂直堆叠。示例如下:
问题在于,根据垂直图的数量,suptitle
(顶部标题)会转到不同的位置。检查以下 5 和 10 图的示例:
5 地块:
这里有 10 个地块:
所以对于每一个地块,我都会得到不同的结果。使用 fig.tight_layout()
没有帮助。
我需要的是让我的文本底部与图表顶部保持一定距离。这个问题有一个通用的答案吗?
我创建了一些最小的工作代码,其中参数化了地块的数量。如果您想重现此问题,请查看。
import datetime
import random
import matplotlib
matplotlib.use('Agg') # Force matplotlib not to use any Xwindows backend.
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.image as mpimg
import matplotlib.gridspec as gridspec
import numpy as np
random.seed(datetime.datetime.now())
#initial parameters
numOfPlots = 2
dataLen = 100
randomRange = 10*dataLen
dpiVal = 180
#create data
xData = list(range(dataLen) for x in range(numOfPlots))
yData = list(random.sample(range(randomRange), dataLen) for x in range(numOfPlots))
#matplotlib initialize plot
gs = gridspec.GridSpec(numOfPlots,1)
plt.cla()
plt.clf()
fig = plt.figure()
ax = None
for i in list(range(numOfPlots)):
if i == 0:
ax = fig.add_subplot(gs[i])
else:
ax = fig.add_subplot(gs[i],sharex=ax)
ax.plot(xData[i], yData[i])
labelSize = 10
ax.set_ylabel("Hi there",size=8)
ax.get_yaxis().set_label_coords(-0.07,0.5)
plt.yticks(size=8)
plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0),useOffset=True)
plt.subplots_adjust(hspace = 0.3)
if i == numOfPlots-1:
plt.xticks(rotation=0,size=7)
max_xticks = 10
xloc = plt.MaxNLocator(max_xticks)
ax.xaxis.set_major_locator(xloc)
ax=plt.gca()
else:
plt.tick_params(
axis='x', # changes apply to the x-axis
labelbottom='off') # labels along the bottom edge are off
ax_right = ax.twinx()
ax_right.yaxis.set_ticks_position('right')
ax_right.set_ylabel("Nice to see you!",size=labelSize)
ax_right.get_yaxis().set_ticks([])
#the following sets the size and the aspect ratio of the plot
fig.set_size_inches(10, 1.8*numOfPlots)
fig.suptitle("Hi there, this is the first line\nAnd this is the second!!!")
fig.savefig("img_"+str(numOfPlots)+".png",bbox_inches='tight',dpi=dpiVal)
我建议尝试一些手动操作:添加文本注释,其中以图形相对坐标为单位的位置。
考虑这两个虚拟示例:
hf,ax = plt.subplots(nrows=3)
hf.text(0.5,0.92,
"Hi there, this is the first line\nAnd this is the second!!!",
horizontalalignment='center')
hf,ax = plt.subplots(nrows=7)
hf.text(0.5,0.92,
"Hi there, this is the first line\nAnd this is the second!!!",
horizontalalignment='center')
结果 "suptitle" 位于完全相同的位置:
我有一个网站可以生成(取决于可用的数据站 运行)任意数量的图(作为图像),它们相互垂直堆叠。示例如下:
问题在于,根据垂直图的数量,suptitle
(顶部标题)会转到不同的位置。检查以下 5 和 10 图的示例:
5 地块:
这里有 10 个地块:
所以对于每一个地块,我都会得到不同的结果。使用 fig.tight_layout()
没有帮助。
我需要的是让我的文本底部与图表顶部保持一定距离。这个问题有一个通用的答案吗?
我创建了一些最小的工作代码,其中参数化了地块的数量。如果您想重现此问题,请查看。
import datetime
import random
import matplotlib
matplotlib.use('Agg') # Force matplotlib not to use any Xwindows backend.
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.image as mpimg
import matplotlib.gridspec as gridspec
import numpy as np
random.seed(datetime.datetime.now())
#initial parameters
numOfPlots = 2
dataLen = 100
randomRange = 10*dataLen
dpiVal = 180
#create data
xData = list(range(dataLen) for x in range(numOfPlots))
yData = list(random.sample(range(randomRange), dataLen) for x in range(numOfPlots))
#matplotlib initialize plot
gs = gridspec.GridSpec(numOfPlots,1)
plt.cla()
plt.clf()
fig = plt.figure()
ax = None
for i in list(range(numOfPlots)):
if i == 0:
ax = fig.add_subplot(gs[i])
else:
ax = fig.add_subplot(gs[i],sharex=ax)
ax.plot(xData[i], yData[i])
labelSize = 10
ax.set_ylabel("Hi there",size=8)
ax.get_yaxis().set_label_coords(-0.07,0.5)
plt.yticks(size=8)
plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0),useOffset=True)
plt.subplots_adjust(hspace = 0.3)
if i == numOfPlots-1:
plt.xticks(rotation=0,size=7)
max_xticks = 10
xloc = plt.MaxNLocator(max_xticks)
ax.xaxis.set_major_locator(xloc)
ax=plt.gca()
else:
plt.tick_params(
axis='x', # changes apply to the x-axis
labelbottom='off') # labels along the bottom edge are off
ax_right = ax.twinx()
ax_right.yaxis.set_ticks_position('right')
ax_right.set_ylabel("Nice to see you!",size=labelSize)
ax_right.get_yaxis().set_ticks([])
#the following sets the size and the aspect ratio of the plot
fig.set_size_inches(10, 1.8*numOfPlots)
fig.suptitle("Hi there, this is the first line\nAnd this is the second!!!")
fig.savefig("img_"+str(numOfPlots)+".png",bbox_inches='tight',dpi=dpiVal)
我建议尝试一些手动操作:添加文本注释,其中以图形相对坐标为单位的位置。
考虑这两个虚拟示例:
hf,ax = plt.subplots(nrows=3)
hf.text(0.5,0.92,
"Hi there, this is the first line\nAnd this is the second!!!",
horizontalalignment='center')
hf,ax = plt.subplots(nrows=7)
hf.text(0.5,0.92,
"Hi there, this is the first line\nAnd this is the second!!!",
horizontalalignment='center')
结果 "suptitle" 位于完全相同的位置: