Using plt.text to print calculated values in a plot


Question

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() 
1
3
7/28/2012 6:59:21 AM

Accepted Answer

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.

2
7/28/2012 7:39:43 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon