如何在散点图中设置图表内的标题位置?

How to set title position inside graph in scatter plot?

MWE: 我希望标题位置与图中相同:

这是我的代码:

import matplotlib.pyplot as plt
import numpy as np
import random 


fig, ax = plt.subplots()

x = random.sample(range(256),200)
y = random.sample(range(256),200)

cor=np.corrcoef(x,y)

plt.scatter(x,y, color='b', s=5, marker=".")
#plt.scatter(x,y, label='skitscat', color='b', s=5, marker=".")
ax.set_xlim(0,300)
ax.set_ylim(0,300)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Correlation Coefficient: %f'%cor[0][1])
#plt.legend()
fig.savefig('plot.png', dpi=fig.dpi)
#plt.show()

但这给出了:

如何固定这个标题位置?

给X轴和Y轴赋两个对应的值。注意!要在图表中添加标题,值应在 (0,1) 区间内。您可以在此处查看示例代码:

import matplotlib. pyplot as plt
A= [2,1,4,5]; B = [3,2,-2,1]
plt.scatter(A,B)
plt.title("title", x=0.9, y=0.9)
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()

在轴内的任意位置移动 title 会变得不必要的复杂。
相反,人们宁愿在所需位置创建一个 text

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

x = np.random.randint(256,size=200)
y = np.random.randint(256,size=200)

cor=np.corrcoef(x,y)

ax.scatter(x,y, color='b', s=5, marker=".")

ax.set_xlim(0,300)
ax.set_ylim(0,300)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.text(0.9, 0.9, 'Correlation Coefficient: %f'%cor[0][1], 
        transform=ax.transAxes, ha="right")

plt.show()