gpt4 book ai didi

Python、Matplotlib : Suptitle with arbitrary number of vertical figures

转载 作者:行者123 更新时间:2023-12-05 07:48:51 32 4
gpt4 key购买 nike

我有一个网站可以生成(取决于运行的可用数据站)任意数量的图(作为图像),这些图相互垂直堆叠。示例如下:

enter image description here

问题在于,根据垂直图的数量,suptitle(顶部标题)会转到不同的位置。检查以下 5 和 10 图的示例:

5 个地 block :

enter image description here

这里有 10 个图:

enter image description here

因此,对于每一个地 block ,我都会得到不同的结果。使用 fig.tight_layout() 没有帮助。

我需要的是让我的文本底部与图表顶部保持一定距离。这个问题有一个通用的答案吗?

我创建了一些最小的工作代码,其中包含参数化的地 block 数量。如果您想重现此问题,请检查一下。

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')

结果的“副标题”位于完全相同的位置:

case1 case2

关于Python、Matplotlib : Suptitle with arbitrary number of vertical figures,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38107451/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com