0

I'm generating graphs in Jupyter using the following code:

import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
from scipy.integrate import quad
import math
from matplotlib.patches import Circle

fig2 = plt.figure(figsize=(10,8))
plt.subplot(1, 1, 1)
plt.plot(2, 5, marker='*', markersize=25, color='gold')
plt.plot(2, -5, marker='*', markersize=25, color='gold')
plt.plot(3, 0, marker='*', markersize=25, color='gold')
plt.xlabel(r"$x [rg]$", fontsize=20)
plt.ylabel(r"$y [rg]$", fontsize=20)
circle = Circle((0, 0), 1, color='black')
plt.gca().add_patch(circle)
plt.gca().set_aspect('equal')
plt.axis([-10, 30, -10, 10])
plt.tick_params(axis='both', labelsize=20)

The generated image has the shape enter image description here

However, I would like it to resemble the characteristics of this image below. With the same default font used in LaTeX for both text and numbers and with the grid of small 'dashes' on all four sides of the plot. How can I achieve this? enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
  • Your side question is a duplicate of many posted questions, such as [here](https://stackoverflow.com/q/6998697/8508004) and [here](https://stackoverflow.com/q/55458260/8508004). Since you don't want the label on that side, check [here](https://stackoverflow.com/q/20936658/8508004) and [here](https://stackoverflow.com/q/56576847/8508004) as well. – Wayne Aug 23 '23 at 20:47

3 Answers3

0

For the latex font you need to use mpl.rcParams["text.usetex"] = True and a proper latex installation.

For the ticks formatting, you need to set the arguments of the .tick_params() function.

import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.patches import Circle

mpl.rcParams["text.usetex"] = True

fig, ax = plt.subplots(figsize=(10, 8))

ax.plot(2, 5, marker="*", markersize=25, color="gold")
ax.plot(2, -5, marker="*", markersize=25, color="gold")
ax.plot(3, 0, marker="*", markersize=25, color="gold")

circle = Circle((0, 0), 1, color="black")
ax.add_patch(circle)

ax.set_xlabel(r"$x [rg]$", fontsize=20)
ax.set_ylabel(r"$y [rg]$", fontsize=20)

ax.set_aspect("equal")
ax.set_xlim(-10, 30)
ax.set_ylim(-10, 10)

ax.tick_params(axis="both", top=True, right=True, labelsize=20, direction="in")

plt.show()

latex style plot

paime
  • 2,901
  • 1
  • 6
  • 17
  • It gives the error ```RuntimeError: Failed to process string with tex because latex could not be found``` – Projetos Programação Aug 23 '23 at 21:05
  • You need a proper latex installation. You will find existing support for that online. Also do check my other answer once you installed latex, using stylesheets to reuse the style across plots. – paime Aug 23 '23 at 21:11
0

There's always this from Matplotlib's documentation on 'Text rendering with LaTeX':

"Matplotlib can use LaTeX to render text. This is activated by setting text.usetex : True in your rcParams, or by setting the usetex property to True on individual Text objects. "

I didn't take that path but you may want to combine it with some of the approaches below.


Getting close without usetex but using Latex in the plot label

This answer shows you how you can use the dollar sign to place Latex in labels.

The tricks with the ticks are annotated in the code.

This gets you close but you were vague on what you really wanted in a few things and so you'll need to customize some more:

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import sympy as sp
from scipy.integrate import quad
import math
from matplotlib.patches import Circle

matplotlib.rcParams['font.family'] = ['serif'] # based on https://matplotlib.org/stable/tutorials/text/text_props.html

fig2 = plt.figure(figsize=(10,8))
plt.subplot(1, 1, 1)
plt.plot(2, 5, marker='*', markersize=25, color='gold')
plt.plot(2, -5, marker='*', markersize=25, color='gold')
plt.plot(3, 0, marker='*', markersize=25, color='gold')
#plt.xlabel(r"$x [rg]$", fontsize=20)
#plt.ylabel(r"$y [rg]$", fontsize=20)
circle = Circle((0, 0), 1, color='black')
plt.gca().add_patch(circle)
plt.gca().set_aspect('equal')
plt.axis([-10, 30, -10, 10])
plt.gca().set_ylabel(r'x[rg]' "\n" r'$x[rg]$' "\n" r'$r \slash r_S$',
          fontsize=20, rotation = 0, labelpad=35) # rotation based on https://stackabuse.com/rotate-axis-labels-in-matplotlib/
# multiline labels based on https://stackoverflow.com/a/2666270/8508004 (just added for development of example because OP unclear on actual label)
# use of `labelpad` is to complement `set_label_position` use, see next line
plt.gca().yaxis.set_label_position("right") # label on right based on https://stackoverflow.com/a/64363955/8508004
plt.gca().set_xlabel(r"$y [rg]$", fontsize=20, rotation = 0)

plt.gca().minorticks_on() # based on https://stackoverflow.com/a/57280702/8508004
plt.gca().yaxis.set_ticks_position('both')# Ticks on all 4 sides; based on https://stackoverflow.com/a/56577545/8508004                                                                                                                                                                                                                                 
plt.gca().xaxis.set_ticks_position('both') # based on https://stackoverflow.com/a/56577545/8508004
plt.gca().xaxis.set_tick_params(which='both', direction = 'in')# ticks facing inward direction based on https://stackoverflow.com/q/71366709/8508004
plt.gca().yaxis.set_tick_params(which='both', direction = 'in')# ticks facing inward based on https://stackoverflow.com/q/71366709/8508004

plt.tick_params(axis='both', labelsize=20)

enter image description here

Wayne
  • 6,607
  • 8
  • 36
  • 93
  • It gives the error ```RuntimeError: Failed to process string with tex because latex could not be found``` – Projetos Programação Aug 23 '23 at 21:05
  • You not having Latex installed correctly is a different issue than your current questions in your post. To skip getting that installation accomplished, you can go [here](https://github.com/binder-examples/requirements) and click `launch binder`. The session that comes up will have Latex installed already. **First**, you'll need to run `%pip install sympy` in the notebook to use your code or mine in that temporary session. Download anything useful your make because it is temporary. – Wayne Aug 23 '23 at 21:09
0

If it comes that you reuse this styling quite often, you can save it in a style sheet and just import it, as follows:

(Check matplotlib.rcParams for the properties you can set)

The stylesheet (e.g. "./my_latex_style.mplstyle"):

text.usetex : True

axes.labelsize : 20

xtick.bottom : True
xtick.top : True
xtick.direction : "in"
xtick.labelsize : 20

ytick.left : True
ytick.right : True
ytick.direction : "in"
ytick.labelsize : 20

Usage:

import matplotlib.pyplot as plt
from matplotlib.patches import Circle

plt.style.use("./my_latex_style.mplstyle")

fig, ax = plt.subplots(figsize=(10, 8))

ax.plot(2, 5, marker="*", markersize=25, color="gold")
ax.plot(2, -5, marker="*", markersize=25, color="gold")
ax.plot(3, 0, marker="*", markersize=25, color="gold")

circle = Circle((0, 0), 1, color="black")
ax.add_patch(circle)

ax.set_xlabel(r"$x [rg]$")
ax.set_ylabel(r"$y [rg]$")

ax.set_aspect("equal")
ax.set_xlim(-10, 30)
ax.set_ylim(-10, 10)

plt.show()

Latex style plot from stylesheet

Note: Relative import of the style sheet is buggy only for 3.7.0, fixed in 3.7.1, see issue #25242.

paime
  • 2,901
  • 1
  • 6
  • 17