Stripers247
Stripers247

Reputation: 2335

Using plt.text to print calculated values in a plot

Hi Is there a way to print values calculated by a script directly into the plot that is being made?

For example say I have a data file that I read in. Then I want to calculate the total number of entries, the sum of the entries, the average and standard deviation. How can I then print these vales right on to the histogram that I then plot?

I looked here http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.text, but it was not very helpful. Thanks in advance

Example

file = 'myfile.txt'
d = np.loadtxt(file)
C = d[:,3]

S = sum(C))   
avg = np.mean(C)
sigma = np.std(C)
N = len(C)

I tried this but it did not work

n, nbins, patches = plt.hist(C, 20)
plt.title("My Histogram")
plt.text(0,0, 'Sum of vales ='S  '\n' 'Total number of entries = ' N  
         '\n' 'Avg= 'avg   '\n'   'Standard Deviation = ' sigma)
ply.show() 

Upvotes: 3

Views: 17727

Answers (1)

xiaowl
xiaowl

Reputation: 5217

I think you forget to call show() after plot(...)

Update

I chat with OP in comments. It turns out that the problem is syntax error. His original code

plt.text(0,0, 'Sum of vales ='S  '\n' 'Total number of entries = ' N '\n' 'Avg= 'avg   '\n'   'Standard Deviation = ' sigma)

He try to concat string in this way 'some string' variable 'another string'. He ask me why 'some string' ' another string' is OK, because Python automatically join adjacent strings into one single string. In this case, he gets 'some string another string', which is a valid python statement.

Upvotes: 2

Related Questions