图例标签中的 matplotlib 乳胶与轴标签中的 [英] matplotlib latex in legend label vs in axis label

查看:49
本文介绍了图例标签中的 matplotlib 乳胶与轴标签中的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于matplotlib,您可以使用tex命令语法标记图例和轴标签.您应该将r放在字符串的前面:r我的tex标签".但我不明白的是为什么图例标签关心轴标签确实关心.

For matplotlib, you can label legends and axis labels using tex command syntax. You're supposed to prepend r to the string: r"my tex label". But what I don't understand is why the legend label doesn't care and yet the axis label does care.

为什么轴标签的行为与图例标签不同(反之亦然)?

Why do the axis labels behave differently than the legend label (or vice versa)?

MWE1 - 崩溃

## Hello World! I crash!
import numpy as np
import matplotlib.pyplot as plt
x = np.ones(5)
plt.plot(x, x, label="$\bar{x}$ (but not really)")
plt.xlabel("$\bar{y}$ (but not really)") # I cause the crash
plt.show()

MWE2-不会崩溃

import numpy as np
import matplotlib.pyplot as plt
x = np.ones(5)
plt.plot(x, x, label="$\bar{x}$ (but not really)") # I still don't need prepended r
plt.xlabel(r"$\bar{y}$ (but not really)")
plt.show()

推荐答案

这是不公平的比较.由于没有图例,因此从未使用过MWE2 get的绘图标签.因此它不会引发任何错误.一旦您使用 plt.legend() 生成此图例,它当然会导致与您期望的所有其他包含 MathText 命令且不是原始字符串的字符串相同类型的错误.

That's no fair comparisson. The plot label from MWE2 get's never used, because there is no legend; therefore it will not raise any error. Once you produce this legend using plt.legend() it will of course cause the same kind of error that you'd expect from all other strings that contain MathText commands and are no raw strings.

此崩溃:

import numpy as np
import matplotlib.pyplot as plt
x = np.ones(5)
plt.plot(x, x, label="$\bar{x}$ (but not really)") 
plt.xlabel(r"$\bar{y}$ (but not really)")
plt.legend()
plt.show()

这不会崩溃,因为所有字符串都是原始字符串

This does not crash, as all strings are raw strings

import numpy as np
import matplotlib.pyplot as plt
x = np.ones(5)
plt.plot(x, x, label=r"$\bar{x}$ (but not really)") 
plt.xlabel(r"$\bar{y}$ (but not really)")
plt.legend()
plt.show()

这篇关于图例标签中的 matplotlib 乳胶与轴标签中的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆