简体   繁体   English

Matplotlib tight_layout 设置矩形元组

[英]Matplotlib tight_layout set rect tuple

I have created the following code, which prints a plot and formats the axis labels and ticks in a way that is useful to me.我创建了以下代码,它打印 plot 并以对我有用的方式格式化轴标签和刻度。 I have a problem with tight_layout, which leaves my vertically rotated x-axis tick labels as well as the x-axis label outside the figure window.我遇到了tight_layout 的问题,它使我的垂直旋转的x 轴刻度标签以及x 轴label 在图形window 之外。

To try and solve the problem, what I did was to manually rescale the plot window, and set the rect tuple manually from the figure window.为了尝试解决这个问题,我所做的是手动重新调整 plot window,并从图 window 手动设置矩形元组。 After some tries, I found that the optimal values for (left, bottom, right, top) in my case were [0.163, 0.391, 0.905, 0.977].经过一些尝试,我发现(左、下、右、上)的最佳值在我的情况下是 [0.163, 0.391, 0.905, 0.977]。 Next, I thought I should incorporate that to my code, so that my plots emerge with correct sizing in the first place: To that end, I used the command:接下来,我认为我应该将其合并到我的代码中,以便我的绘图首先以正确的大小出现:为此,我使用了以下命令:

fig.tight_layout(rect=[0.163, 0.391, 0.905, 0.977]) fig.tight_layout(rect=[0.163, 0.391, 0.905, 0.977])

However, it did not work, and the figure emerges with different rect values than the ones I set.但是,它不起作用,并且该图形出现的矩形值与我设置的值不同。

Question 1: How can I set the rect values from my code, rather than setting them manually?问题 1:如何从我的代码中设置 rect 值,而不是手动设置它们?

Question 2: Is there a better/easier alternative to achieve the desired functionality?问题 2:是否有更好/更简单的替代方案来实现所需的功能?

# dt_objects is a list of datetime objects. My x-axis is timestamps
# for y_axis, set any series. The code will set the y axis based on the min,max value of y-values

matdates=date2num(dt_objects)
x_axis=matdates

fig,ax = plt.subplots()
ax.plot_date(x_axis,y_axis,markersize=8)
ax.axhline(y=y_axis.mean(),linestyle='--',color='red',alpha=0.5)

ax.xaxis.set_major_locator(AutoDateLocator(minticks=1, maxticks=5))         #Set position of Major X ticks
ax.xaxis.set_minor_locator(AutoDateLocator(minticks=10, maxticks=30))       #Set position of Minor X ticks
ax.xaxis.set_major_formatter( DateFormatter('%Y/%m/%d-%H:%M:%S'))           #Set format of Major X ticks
ax.xaxis.set_minor_formatter( DateFormatter('%H:%M:%S'))                    #Set format of X ticks
ax.tick_params(axis='x',which='major',rotation=90,labelsize=14)                          #Set parameters of Major X ticks    
ax.tick_params(axis='x',which='minor',rotation=80,labelsize=12)                          #Set parameters of Major X ticks      
plt.setp(ax.get_xticklabels(), fontsize=14, fontweight="bold")              #Set font of Major X ticks  

ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))                    #Set format of Major Y ticks
ax.tick_params(axis='y',which='major',labelsize=14)
calculateYpadding=(y_axis.max()-y_axis.min())*0.1                           # Padding is 10% of the max difference in y values :)
ax.set_ylim(round(y_axis.min(),2)-calculateYpadding, round(y_axis.max(),2)+calculateYpadding)         #Set boundaries of Y axis
ax.yaxis.set_major_locator(MaxNLocator(nbins = 'auto',min_n_ticks = 5)) 
plt.grid()

ax.set_xlabel("Time",style='italic',fontsize=14)
ax.xaxis.set_label_coords(1.08, -0.1)

ax.set_ylabel(str(MeasurementType),labelpad=10,style='italic', fontsize=14)
#ax.yaxis.set_label_coords(-0.1, 0.5)
#plt.xlabel("Time",horizontalalignment='right', position=(1,60))\
    
#ax.set_title(str(MeasurementType),fontweight="bold", pad=20,fontsize=20)
rstButton.config(state=tk.NORMAL)
fig.tight_layout(rect=[0.163, 0.391, 0.905, 0.977])
plt.show()

EDIT: Since I was told my question is not clear, I am including two screenshots to better explain the problem.编辑:因为有人告诉我我的问题不清楚,所以我提供了两个屏幕截图以更好地解释问题。 Here is the result of the above-mentioned code.这是上述代码的结果。 Also, on the bottom left, you can see on the window that top, bottom, left, right have different values than the ones set at rect tuple in my code.此外,在左下角,您可以在 window 上看到,顶部、底部、左侧、右侧的值与我的代码中在 rect 元组中设置的值不同。

在此处输入图像描述

My desired output is this:我想要的 output 是这样的:

在此处输入图像描述

It is achieved by manually tweaking the parameters of the figure, until it reaches a point that is satisfactory.它是通过手动调整图形的参数来实现的,直到达到令人满意的程度。 It is from here that i extracted the values and placed them in the rect tuple, but it did not work.正是从这里我提取了值并将它们放在 rect 元组中,但它不起作用。 Hopefully it is clearer now what I want to achieve, and what the problem is.希望现在更清楚我想要实现什么,以及问题是什么。

EDIT 2: Here are the results of the suggested solution编辑2:这是建议解决方案的结果

fig,ax = plt.subplots(constrained_layout=True)

As you can see, the labels of both axles are not correctly placed.如您所见,两个轴的标签都没有正确放置。

在此处输入图像描述

Try:尝试:

fig, ax = plt.subplots(constrained_layout=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM