How to set title position inside graph in scatter plot?

2989 views python
2

MWE: I would like the title position same as in the graph : enter image description here

Here is my code :

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

But this gives :
enter image description here

How do I fix this title position?

answered question

2 Answers

6

use this code:

x= [2,1]; y = [3,2]
plt.scatter(x,y)
plt.title("title", y=0.5)
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()

posted this
4

It will be unnecessarily complicated to move the title at some arbitrary position inside the axes.
Instead one would rather create a text at the desired position.

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

enter image description here

posted this

Have an answer?

JD

Please login first before posting an answer.