Reputation: 2983
While trying to loop over equations on matplotlib, I only get the last text from plt.text()
. How can I iterate over matplotlib figures and annotate equation for each plot? Also the plt.savefig()
function does not save the figures.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from scipy.stats import pearsonr
df=pd.read_csv(r'C:\GISN21\Ex_04\data5\data3_4.txt',sep="\t",header=0)
df2=df.loc[:, df.columns != 'Station']
def calculate_pvalues(df):
df = df.dropna()._get_numeric_data()
dfcols = pd.DataFrame(columns=df.columns)
pvalues = dfcols.transpose().join(dfcols, how='outer')
for r in df.columns:
for c in df.columns:
pvalues[r][c] = round(pearsonr(df[r], df[c])[1], 8)
if pvalues[r][c] < 0.05:
i=0
if r != c:
#best fit line
(m,b)=np.polyfit(df[r] ,df[c] ,1)
equation = 'y = ' + str(round(m,4)) + 'x' ' + ' + str(round(b,4))
f = plt.figure()
plt.text(0.5,0.5, equation)
plt.savefig("correlation{i}.png".format(i=i))
ax = f.add_subplot(1,1,1)
p = sns.regplot(x=df[r],y=df[c],data=df,ax=ax)
return pvalues
sns.pairplot(df,kind='scatter')
plt.savefig('correlation.png')
plt.show()
Upvotes: 1
Views: 1358
Reputation: 10320
By default, plt.text
uses data coordinates, and matplotlib doesn't automatically adjust the limits to include text that is not within the data limits. So unless (0.5, 0.5)
is within the limits when plt.text
is called it will not be visible. If this is the case, you can resolve the issue by using axis coordinates. This can be done by supplying the axis transformation to the transform
keyword, i.e.
plt.text(0.5, 0.5, equation, transform = plt.gca().transAxes)
Will place the Text
instance in the center of the current axes.
Upvotes: 3