简体   繁体   English

Matplotlib 标题和轴 label 填充

[英]Matplotlib title and axis label padding

I'm just starting out experimenting with Matplotlib today.我今天刚开始尝试 Matplotlib。 I've spent the last few hours trying to fix the positioning of the title and axis labels to no avail.我花了过去几个小时试图修复标题和轴标签的位置,但无济于事。 I figured out to fix the spacing between the title and top of the chart and the axis labels and ticks using the padding parameter.我想出使用填充参数来修复图表的标题和顶部以及轴标签和刻度之间的间距。 I can't figure out how to make it so that the title is not crammed to top of the figure and the x/y axis labels aren't crammed to the left/bottom of the figure.我不知道如何做到这一点,这样标题就不会被塞到图形的顶部,x/y 轴标签也不会被塞到图形的左侧/底部。

Below is an example that has nothing to do with my actual problem other than illustrating the formatting issue.下面是一个示例,除了说明格式问题外,与我的实际问题无关。

import matplotlib.pyplot as plt
import numpy as np

#create data
A = 5
f = 0.5
t = np.arange(0,10,0.01)
y = A * np.sin(2*np.pi*f*t)

#create plot
fig, ax = plt.subplots()
fig.set_size_inches(8*(16/9),8)
ax.plot(t,y)

#format plot
ax.spines.top.set_visible(False)
ax.spines.right.set_visible(False)
ax.set_title('Need this title to move down without moving into subplot so that it is not crammed on top',pad=20)
ax.set_ylabel('Need this label to move to the right',labelpad=20)
ax.set_xlabel('Need this label to move up',labelpad=20)

格式问题示例

Any suggestions as to how to increase the margins between the outside of the title/labels and the edge of the figure would be greatly appreciated.任何关于如何增加标题/标签外部与图形边缘之间的边距的建议将不胜感激。

You can try something like that:你可以尝试这样的事情:

import matplotlib.pyplot as plt
import numpy as np

#create data
A = 5
f = 0.5
t = np.arange(0, 10, 0.01)
y = A * np.sin(2 * np.pi * f * t)

#create plot
fig, ax = plt.subplots()
fig.set_size_inches(8 * (16 / 9), 8)
ax.plot(t, y)

#format plot
ax.spines.top.set_visible(False)
ax.spines.right.set_visible(False)

ax.set_title("Title", y=-0.1)

ax.set_xlabel("x-label")
ax.xaxis.set_label_position("top") 

ax.set_ylabel("y-label")
ax.yaxis.set_label_position("right") 

在此处输入图像描述

If you want to move x/y-ticks on top/to the right as well, then use the following commands:如果您还想在顶部/右侧移动 x/y 刻度,请使用以下命令:

ax.xaxis.tick_top()
ax.yaxis.tick_right()

and then modify:然后修改:

ax.spines.top.set_visible(False)
ax.spines.right.set_visible(False)

to

ax.spines.bottom.set_visible(False)
ax.spines.left.set_visible(False)

在此处输入图像描述

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

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