Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text display with matplotlib

I'm having a problem with the plt.text() method in matplotlib and I am hoping someone can help me. Below is a basic linear regression example where I would like to display some text (slope = ) and the actual slope of the line on the graph:

import csv
import scipy as sp
import scipy.stats
import matplotlib.pyplot as plt

x, y = sp.loadtxt('nums.csv', delimiter=',', usecols=(0,1), unpack=True)
linear_reg = slope, intercept, r_value, p_value, std_err = sp.stats.linregress(x, y)
plt.title('SO Regression Example')
plt.text(2, 30, r'slope=', slope, fontsize=15)
plt.plot(x, y)
plt.show()

The above code throws an AttributeError: 'numpy.float64' object has no attribute 'items'

My code works fine if I remove either r'slope = ' or slope from line 9. For example both of these lines work just fine:

plt.text(2, 30, slope, fontsize=15) # displays: 0.82785632403515463

or

plt.text(2, 30, r'slope =', fontsize=15) # displays: slope

Does anyone know how I can make this plot display both items: (slope = 0.82785632403515463)

Right now, I am using a hack by using two separate plt.text() lines and manually positioning the data:

plt.text(2, 30, r'slope=', fontsize=15)
plt.text(7, 30, slope, fontsize=15)

There must be an easier way?

like image 762
drbunsen Avatar asked Sep 17 '25 03:09

drbunsen


1 Answers

str='slope'+str(slope)
plt.text(2, 30, str, fontsize=15)

or just plt.text(2, 30, r'slope='+str(slope), fontsize=15)

like image 101
ev-br Avatar answered Sep 18 '25 16:09

ev-br