matplotlib - animeshtrivedi/notes GitHub Wiki

matplotlib

Follow here: https://matplotlib.org/stable/users/explain/quick_start.html#quick-start

Excellent set of examples to read: https://matplotlib.org/stable/gallery/index.html

Example:

Concepts

Coordinates

https://matplotlib.org/stable/users/explain/artists/transforms_tutorial.html

It has multiple coordinate system, where data and axes is most commonly used. Here is an example of using data and axes coordinates when trying to place the bounding box for the legend. This uses normalized axis

ax.text(0.05, 0.5, "A", transform=ax.transAxes, fontsize=16, fontweight='bold', va='top')

This uses data driven coordinates, see transData and (6, 0.5) setup

ax.text(6, 0.5, "A", transform=ax.transData, fontsize=16, fontweight='bold', va='top')

Capabilities:

    # loc are normaled to 1, 1 values 
    ax.legend(title='Fruit color', loc=(1,1)) 
    # This automaticlaly manages the size! 
    # https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tight_layout.html
    plt.tight_layout()
    plt.savefig("./x.pdf", bbox_inches='tight', dpi=300)
    plt.show()

Old notes

Layout issue: What does the argument mean in fig.add_subplot(111)?

# fig.add_subplot(ROW,COLUMN,POSITION)
# ROW=number of rows
# COLUMN=number of columns
# POSITION= position of the graph you are plotting

fig = plt.figure()
fig.add_subplot(1, 2, 1)   #top and bottom left
fig.add_subplot(2, 2, 2)   #top right
fig.add_subplot(2, 2, 4)   #bottom right 
plt.show()

image

location of the legend

How to put the legend outside the plot

markers for lines formatting

matplotlib.markers : https://matplotlib.org/stable/api/markers_api.html#module-matplotlib.markers

Figure and subplots

A image can contain multiple subplots in a grid, the default we work with is 1x1

https://stackoverflow.com/questions/34162443/why-do-many-examples-use-fig-ax-plt-subplots

Setup debugging

You will get this error when running this basic code example: https://matplotlib.org/stable/tutorials/pyplot.html#introduction-to-pyplot

(.venv) atr@u24clean:~/src/python-fio-automation$ python3
Python 3.12.3 (main, Apr 10 2024, 05:33:47) [GCC 13.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib.pyplot as plt
>>> plt.plot([1, 2, 3, 4])
[<matplotlib.lines.Line2D object at 0x7f8fcd70f740>]
>>> plt.ylabel('some numbers')
Text(0, 0.5, 'some numbers')
>>> plt.show()
<stdin>:1: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown
>>> matplotlib.get_backend()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'matplotlib' is not defined
>>> import matplotlib
>>> matplotlib.get_backend()
'agg'
>>> 

:1: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown Source: https://pyimagesearch.com/2015/08/24/resolved-matplotlib-figures-not-showing-up-or-displaying/ and https://stackoverflow.com/questions/77507580/userwarning-figurecanvasagg-is-non-interactive-and-thus-cannot-be-shown-plt-sh

Install the following packages:

sudo apt get install tcl-dev tk-dev  python3-tk PyQt6
# login with X forwarding 
ssh -X 

Then it should work out.

There seems to be further issues in the parsing script with like:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/home/atr/src/python-fio-automation/.venv/lib/python3.12/site-packages/matplotlib/texmanager.py", line 250, in _run_checked_subprocess
    report = subprocess.check_output(
             ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.12/subprocess.py", line 466, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.12/subprocess.py", line 548, in run
    with Popen(*popenargs, **kwargs) as process:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.12/subprocess.py", line 1026, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/lib/python3.12/subprocess.py", line 1955, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'latex'

I am going to ignore debugging this as the target in the VM is PDF output type. But seems like I need to install the latex distribution which is not needed, here. OK found the culprit, it was type-1 font fixes:

# Switch to Type 1 Fonts.
#matplotlib.rcParams['text.usetex'] = True
#plt.rc('font', **{'family': 'serif', 'serif': ['Times']})
⚠️ **GitHub.com Fallback** ⚠️