使用 Matplotlib 和 TeX 统一间距 [英] Uniform spacing with Matplotlib and TeX

查看:51
本文介绍了使用 Matplotlib 和 TeX 统一间距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为数学课绘制一些图表,但我无法在情节图例中完全正确地获得和平定义的间距.我目前正在使用

I am drawing up some graphs for a math class, and I can't get the spacing for peacewise definitions quite right in the plot legend. I am currently using

\,

对于TeX中的单个空格,但是遇到这样的情况,一个可能比另一个稍微远一些,这可能是因为左边的方程式占用了多少空间.这是我的代码

for a single space in TeX, but run into a situation where one is slightly farther up than other maybe due to how much the equations to the left take up. Here is my code

import matplotlib.pyplot as plt
import numpy as np
import math as math

# 0-1
x = np.linspace(0, 1)
y = np.power(x, 2)
plt.plot(x, y, label=r"$t^2 \,\,\,\,\,\, 0 \leq t \leq 1$")

#1-2
x = [1,2]
y = [1,1]
plt.plot(x, y, label=r"$1 \,\,\,\,\,\,\, 1 < t \leq 2$")

#2-3
x = np.linspace(2, 3)
y = 3-x
plt.plot(x, y, label=r"$3 - t \,\,\,\, 2 < t \leq 3$")


plt.grid()
plt.axis([0,3,0,1.5])
plt.legend(loc='upper right')
plt.show()

这是结果

如何以一种无论左侧像素大小如何都可以正常工作的方式对其进行有效格式化?

How do I format this effectively in a way that will always work regardless of the pixel sizes on the left?

推荐答案

您当然可以通过访问较低级别的LaTeX来改善间距.首先,在图的顶部运行:

You can certainly improve on the spacing by accessing a lower level of LaTeX. To begin, at the top of your plots run:

from matplotlib import rc
rc('text', usetex=True)

使用\makebox\hfill 你可以填充两个部分之间的空间:

Using a combination of \makebox and \hfill you can pad out the spaces between the two sections:

label=r"\makebox[4cm]{$t^2$ \hfill $0 \leq t \leq 1$}"
label=r"\makebox[4cm]{$1$ \hfill $1 < t \leq 2$}"
label=r"\makebox[4cm]{$3 - t$ \hfill $2 < t \leq 3$}"

诚然,这并不完美,但是通过多个 \makebox 和填充的组合,您可以微调您需要的内容.理想情况下,您可以编写一个感知"多行 TeX 块的自定义图例处理程序,但我确信这并非易事.

Admittedly this isn't perfect, but with a combination of multiple \makebox and fills you can fine tune what you need. Ideally, you could write a custom legend handler that is "aware" of a multi-line block of TeX, but I'm sure this is non-trivial.

这篇关于使用 Matplotlib 和 TeX 统一间距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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