【问题标题】:How do I write a Latex formula in the legend of a plot using Matplotlib inside a .py file?如何在 .py 文件中使用 Matplotlib 在绘图的图例中编写 Latex 公式?
【发布时间】:2019-03-03 21:24:52
【问题描述】:

我正在用 Python(.py 文件)编写脚本,并且正在使用 Matplotlib 绘制数组。 我想在情节中添加一个带有公式的图例,但我无法做到。 我以前在 IPython 或终端中做过这个。在这种情况下,写这样的东西:

legend(ur'$The_formula$')

完美运行。但是,当我从终端/IPython 调用我的 .py 脚本时,这不起作用。

【问题讨论】:

标签: python matplotlib latex


【解决方案1】:

最简单的方法是在绘制数据时分配标签, 例如:

import matplotlib.pyplot as plt
ax = plt.gca()  # or any other way to get an axis object
ax.plot(x, y, label=r'$\sin (x)$')

ax.legend()

【讨论】:

  • 谢谢!这工作得很好。除了当您想在图例/轴中编写公式时需要“r”这一事实。
  • 你用的是什么版本的python和mpl?如果我使用 ax.plot(x,y,label=r'$\sin (x)$'),我会收到带有“$\\sin$”的 LaTeX 错误。 (我是 2.7.3 python 和前沿 mpl)
  • 我使用 Python 2.7.3 和 Mpl 1.1.1。
  • 美丽的谢天谢地
  • 如果使用black 自动格式化,单引号会自动转换为双引号。这打破了乳胶解释并按原样显示字符。为了避免这种情况,可以输入:label=r"""$\sin (x)$"""
【解决方案2】:

为标签编写代码时:

import pylab

# code here

pylab.plot(x,y,'f:', '$sin(x)$')

所以也许pylab.legend('$latex here$')

编辑:

u 用于 unicode 字符串,试试r'$\latex$'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多