Skip to content

Latest commit

 

History

History
88 lines (54 loc) · 2.86 KB

401read14.md

File metadata and controls

88 lines (54 loc) · 2.86 KB

Matplotlib, what is it?

The single most used Python package for 2D-graphics.

How do I make a simple plot?

The first step is to get the data for the sine and cosine functions:

import numpy as np

X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C, S = np.cos(X), np.sin(X)

# X is now a NumPy array with 256 values ranging from -π to +π (included). C is the cosine (256 values) and S is the sine (256 values).

Now run the example in the command line:

$ python example.py

You should get something like this:

Can I customize my plot?

Yes!

You can customize the labels, the properties of the lines.

You can set the limits of the lines, the ticks and the tick labels.

You can even move the spines and axis containers of your plot.

Want to remind the user which information they are looking at? Add and update the legend so they can see what's going on.

Make the plot unique

  • Figures, A figure is the windows in the GUI that has "Figure #" as title.

  • Subplots, With subplot you can arrange plots in a regular grid. You need to specify the number of rows and columns and the number of the plot.

  • Axes, Axes are very similar to subplots but allow placement of plots at any location in the figure. So if we want to put a smaller plot inside a bigger one we do so with axes.

  • Ticks, Matplotlib provides a totally configurable system for ticks. There are tick locators to specify where ticks should appear and tick formatters to give ticks the appearance you want.

Add animations to make your plot even more unique

Here's how you do it:

def update(frame):
    global P, C, S

    # Every ring is made more transparent
    C[:,3] = np.maximum(0, C[:,3] - 1.0/n)

    # Each ring is made larger
    S += (size_max - size_min) / n

    # Reset ring specific ring (relative to frame number)
    i = frame % 50
    P[i] = np.random.uniform(0,1,2)
    S[i] = size_min
    C[i,3] = 1

    # Update scatter object
    scat.set_edgecolors(C)
    scat.set_sizes(S)
    scat.set_offsets(P)

    # Return the modified object
    return scat,
    
## tell matplotlib to use this function as an update function for the animation and display the result

animation = FuncAnimation(fig, update, interval=10, blit=True, frames=200)
# animation.save('rain.gif', writer='imagemagick', fps=30, dpi=40)
plt.show()

This is only scratching the surface of what matplotlib can do. There is much more information on their github: https://github.com/rougier/matplotlib-tutorial#introduction