问题
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
\,
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()
Here is the result
How do I format this effectively in a way that will always work regardless of the pixel sizes on the left?
回答1:
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)
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$}"
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.
来源:https://stackoverflow.com/questions/16803885/uniform-spacing-with-matplotlib-and-tex