在Python中使用TeX在matplotlib标签中添加换行符?
如何在 matplotlib 中向绘图标签(例如 xlabel 或 ylabel)添加换行符?例如,
plt.bar([1, 2], [4, 5])
plt.xlabel("My x label")
plt.ylabel(r"My long label with $\Sigma_{C}$ math \n continues here")
理想情况下,我希望 y 标签也居中。有办法做到这一点吗?重要的是标签同时包含 TeX(包含在“$”中)和换行符。
How can I add a newline to a plot's label (e.g. xlabel or ylabel) in matplotlib? For example,
plt.bar([1, 2], [4, 5])
plt.xlabel("My x label")
plt.ylabel(r"My long label with $\Sigma_{C}$ math \n continues here")
Ideally I'd like the y-labeled to be centered too. Is there a way to do this? It's important that the label have both TeX (enclosed in '$') and the newline.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以两全其美:自动“转义”LaTeX 命令和换行符:(
不是使用三行,而是用单个空格分隔字符串是另一种选择)。
事实上,Python 会自动连接彼此跟随的字符串文字,您可以混合原始字符串 (
r"…"
) 和带有字符插值的字符串 ("\n"
) 。You can have the best of both worlds: automatic "escaping" of LaTeX commands and newlines:
(instead of using three lines, separating the strings by single spaces is another option).
In fact, Python automatically concatenates string literals that follow each other, and you can mix raw strings (
r"…"
) and strings with character interpolation ("\n"
).您的示例正是如何完成的,您使用
\n
。不过,您需要去掉 r 前缀,这样 python 就不会将其视为原始字符串Your example is exactly how it's done, you use
\n
. You need to take off the r prefix though so python doesn't treat it as a raw string只需将字符串与非原始字符串形式的换行符连接起来即可。
Just concatenate the strings with a newline that isn't in raw string form.
以下 matplotlib python 脚本创建带有换行符的文本
)以下内容没有换行符。注意文本前面的 r
The following matplotlib python script creates text with new line
)The following does not have new line. Notice the r before the text
如果有人想要 TeX(例如部分粗体文本)和一个新行并且其中有一个百分号(我挣扎的时间比我想要的要长):
返回:
In case anyone wants TeX (e.g. for partly bold text) and a new line AND has a percentage sign in it (I struggled longer than I wanted):
Returns: