【问题标题】:How to set title position inside graph in scatter plot?如何在散点图中设置图表内的标题位置?
【发布时间】:2019-04-08 01:06:03
【问题描述】:

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

但这给出了:

如何修复这个标题位置?

【问题讨论】:

    标签: python matplotlib position title scatter-plot


    【解决方案1】:

    为 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()
    

    【讨论】:

    • 你应该添加一些解释,让读者知道你做了什么以及你在哪里做了
    • 我比较着急,下次去,谢谢指教!
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2018-11-21
      • 2017-07-08
      • 1970-01-01
      • 2020-01-03
      • 2016-07-26
      • 1970-01-01
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多