Uniform distance with Matplotlib and TeX

I draw some graphs for a math class, and I can’t get an interval for worldly definitions, quite right in the plot legend. I am currently using

\, 

for one space in TeX, but they will encounter a situation where it is a little further than the other, maybe due to how many equations are left. 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 can I format this efficiently so that it always works regardless of the pixel sizes on the left?

+4
source share
1 answer

You can, of course, improve the interval by turning to a lower LaTeX level. To get started, at the top of your sites, do:

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

Using a combination of \makebox and \hfill you can set spaces between 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$}" 

enter image description here

Admittedly, this is not ideal, but with a combination of a few \makebox and \makebox you can fine-tune what you need. Ideally, you can write your own legend handler that β€œknows” the multi-line TeX block, but I'm sure this is not trivial.

+5
source

Source: https://habr.com/ru/post/1483257/


All Articles