Python绘图实验室

2024-09-28 21:15:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须绘制10个不同的质量剖面图。目前,我正在pyplot的label列中手动输入mass。

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

label是否只接受手动输入的字符串,或者是否有方法指定saylabel = mass,以便它接受变量(在本例中是mass)的值作为输入?


Tags: logplotdistnp质量绘制plt手动
3条回答

标签必须是字符串,格式化数字to exponential format using ^{}

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

我认为最matplotlib的方法是在生成图之后发布一个单独的legend()

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

根据文档(http://matplotlib.org/api/pyplot_api.html):

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

因此,在您的情况下,要获得label = mass,必须在需要时使用label = "%.1E" % mass和其他格式选项。

很可能你得重新考虑你的mass变量。若要获取示例中除数值外手动键入的内容,还需要一个与MASS1等价的字符串,除非将质量值放入数组中并创建在该数组上迭代的绘图。在这种情况下,您可以根据数组索引动态创建MASSX标签:

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))

相关问题 更多 >