我是python和matplotlib库的新手.我使用matplotlib创建了一个散点图,现在我希望在X轴下方添加一个标题.这是我的代码:
from matplotlib import pyplot as plt
import numpy as np
from pylab import *
file = open('distribution.txt', 'r')
txt="I need the caption to be present a little below X-axis"
x=[]
y=[]
for line in file:
new=line.rstrip()
mystring=new.split("\t")
x.append(mystring[0])
y.append(mystring[1])
fig = plt.figure()
ax1 = fig.add_axes((0.1,0.4,0.8,0.5))
ax1.set_title("This is my title")
ax1.set_xlabel('X-axis')
ax1.set_ylabel('Y-axis')
ax1.scatter(x,y, c='r')
fig.text(.05,.05,txt)
plt.xlim(0, 1.05)
plt.ylim(0, 2.5)
plt.show()
Run Code Online (Sandbox Code Playgroud)
正如您在图像中看到的,我的标题位于散点图下方,是否有办法将其精确地置于X轴下方?我的散点图看起来也是矩形的,有没有办法让它像方块一样?
Abu*_*oeb 20
你可以简单地使用figtext.您还可以根据需要更改x和y轴的值.
txt="I need the caption to be present a little below X-axis"
plt.figtext(0.5, 0.01, txt, wrap=True, horizontalalignment='center', fontsize=12)
Run Code Online (Sandbox Code Playgroud)
tac*_*ell 16
就像是:
from matplotlib import pyplot as plt
import numpy as np
txt="I need the caption to be present a little below X-axis"
# make some synthetic data
x = np.linspace(0, 1, 512)
y = np.random.rand(512)*2.3 + .1
fig = plt.figure()
ax1 = fig.add_axes((0.1, 0.2, 0.8, 0.7))
ax1.set_title("This is my title")
ax1.set_xlabel('X-axis')
ax1.set_ylabel('Y-axis')
# make the edge colors match the facecolors
ax1.scatter(x,y, c='r', edgecolors='face')
# center text
fig.text(.5, .05, txt, ha='center')
# use OO interface
ax1.set_xlim([0, 1.05])
ax1.set_ylim([0, 2.5])
# resize the figure to match the aspect ratio of the Axes
fig.set_size_inches(7, 8, forward=True)
plt.show()
Run Code Online (Sandbox Code Playgroud)
可能有用.让这更容易做的是mpl上游的雷达,但我们仍在寻找有人这样做.
首先,我对matplotlib的联合首席开发人员发表回答感到很奇怪.显然,@ tacaswell比我以前更了解matplotlib.但与此同时,他的回答对我来说还不够动态.我需要一个总是基于其位置的标题xlabel,而不能只使用文本注释.
我考虑过简单地更改xlabel添加换行符和标题文本,但这不会明确区分标题,并且您无法执行更改文本大小或在文本字符串中间使其变为斜体的操作.
我通过使用matplotlib的TeX功能解决了这个问题.这是我的解决方案:
from matplotlib import pyplot as plt
from matplotlib import rc
import numpy as np
from pylab import *
rc('text', usetex=True)
file = open('distribution.txt', 'r')
txt="I need the caption to be present a little below X-axis"
x=[]
y=[]
for line in file:
new=line.rstrip()
mystring=new.split("\t")
x.append(mystring[0])
y.append(mystring[1])
fig = plt.figure()
ax1 = fig.add_axes((0.1,0.4,0.8,0.5))
ax1.set_title("This is my title")
ax1.set_xlabel(r'\begin{center}X-axis\\*\textit{\small{' + txt + r'}}\end{center}')
ax1.set_ylabel('Y-axis')
ax1.scatter(x,y, c='r')
plt.xlim(0, 1.05)
plt.ylim(0, 2.5)
plt.show()
Run Code Online (Sandbox Code Playgroud)
我用tacaswell的答案中的随机散点图做了同样的事情,这是我的结果:
一个警告:如果你调整它以获取输入字符串变量,则可能无法正确转义字符串以与TeX一起使用.Stack Overflow已涵盖转义LaTeX代码,网址为/sf/answers/1811285311/.我直接使用它,然后可以采取任意x标签和标题.
正如@Nicky V 提到的。
plt.xlabel('''Butterfly contract traded
Note: c1-c2-c3 indicates the position: long 2 times c2 and short c1 anc c3''')
Run Code Online (Sandbox Code Playgroud)
结果: