Srivatsan
Srivatsan

Reputation: 9363

Python plot label

I have to plot around 10 different mass profiles. At the moment I am manually entering the mass in the label column of pyplot.

plt.plot(np.log(dist_2[1:]/var2['r200'][:20]), np.log(sigma_num_2),'b-o', color = 'b', label = "MASS1 = 7.6x10^13")

Does label only take manually entered strings or is there a way to specify say label = mass so that it takes the value of the variable (in this case mass) as the input?

Upvotes: 1

Views: 9487

Answers (3)

zhangxaochen
zhangxaochen

Reputation: 34047

labels have to be strings, format the number to exponential format using %e:

plt.plot(..., label = "MASS1 = %.1e" % mass[0])

Upvotes: 2

CT Zhu
CT Zhu

Reputation: 54380

I think the most matplotlibish way of doing it would be to issue a separate legend() once the plots were generated.

l_plot=[]
for i in range(10):
    x=arange(10)
    y=random.random(10)
    l_plot.append(plt.plot(x, y, '+-'))
plt.xlim(0,12)
plt.legend([item[0] for item in l_plot], map(str, range(10))) #change it to the plot labels say ['Mass = %f'%item for item in range(10)].
plt.savefig('temp.png')

enter image description here

Upvotes: 1

Mr. Girgitt
Mr. Girgitt

Reputation: 2903

According to documentation (http://matplotlib.org/api/pyplot_api.html):

label string or anything printable with ‘%s’ conversion.

So in your case to get label = mass you have to use label = "%.1E" % mass with additional formatting options if needed.

Most probably you have to rethink your mass variable. To get what you manually typed in the example additionally to a numeric value you need also a string - equivalent to MASS1 unless you put the mass values into an array and create plots iterating over this array. In such case you can create MASSX labels on the fly based on the array index:

indexVal = 0
for massVal in mass: 
    indexVal += 1

    ...code for getting dist_2, var2, sigma_num_2 variables...

    plt.plot(np.log(dist_2[1:]/var2['r200'][:20]), np.log(sigma_num_2),'b-o', color = 'b', label = "MASS%s = %.1E" % (indexVal, massVal))

Upvotes: 2

Related Questions