下标不适用于字符串格式的迷你语言

时间:2018-07-23 15:11:10

标签: python matplotlib legend subscript legend-properties

legend entries中使用matplotlib.plot的标签参数,我试图实现带有下标的动态生成的图标签。

但是,当使用Python的字符串格式化迷你语言(有关更多信息,请参见docs)代替老式的基于%的表示法将变量插入标签字符串时,我得到的是不同的/错误的输出。当使用.format()插入变量时,只有插入字符串的第一个字符是下标,其他字符不是。但是,由于完整的字符串应为下标,所以这是不希望的。

将图例条目与橙色图与绿色图和蓝色图进行比较:

import matplotlib.pyplot as plt


sample_string = 'XY'

# writing contents of `sample_string` directly to label raw string results in desired label
label1 = r"$w_{XY} = 20 \frac{{kg_{XY}}}{{kg_{{xyz}}}}$"
plt.plot(0, 0, 'o', label=label1)

# passing contents by using string format mini-language results in faulty label
label2 = r"$w_{0} = 20 \frac{{kg_{0}}}{{kg_{{xyz}}}}$".format(sample_string)
plt.plot(0, 0.5, 'o', label=label2)

# using old-fashioned %-notation to insert string results in desired label
label3 = r"$w_{%s} = 20 \frac{{kg_{%s}}}{{kg_{{xyz}}}}$" % (sample_string, sample_string)
plt.plot(0, 1, 'o', label=label3)

plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.075), ncol=4)
plt.show()

sample diagram

如何为.format()%表示法实现相同的输出(将橙色数据点的图例条目中的下标与其他两个符号进行比较)?

0 个答案:

没有答案
相关问题