Skip to content

Arseni1919/Learning_matplotlib

Repository files navigation

Learning matplotlib

About

A picture is worth a thousand words, and with Python’s matplotlib library, it fortunately takes far less than a thousand words of code to create a production-quality graphic.

However, matplotlib is also a massive library, and getting a plot to look just right is often achieved through trial and error. Using one-liners to generate basic plots in matplotlib is fairly simple, but skillfully commanding the remaining 98% of the library can be daunting.

The construction

Buttons

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button

freqs = np.arange(2, 20, 3)

fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
t = np.arange(0.0, 1.0, 0.001)
s = np.sin(2*np.pi*freqs[0]*t)
l, = ax.plot(t, s, lw=2)


class Index:
    ind = 0

    def next(self, event):
        self.ind += 1
        i = self.ind % len(freqs)
        ydata = np.sin(2*np.pi*freqs[i]*t)
        l.set_ydata(ydata)
        plt.draw()

    def prev(self, event):
        self.ind -= 1
        i = self.ind % len(freqs)
        ydata = np.sin(2*np.pi*freqs[i]*t)
        l.set_ydata(ydata)
        plt.draw()

callback = Index()
axprev = fig.add_axes([0.7, 0.05, 0.1, 0.075])
axnext = fig.add_axes([0.71, 0.75, 0.2, 0.175])
bnext = Button(axnext, 'Next')
bnext.on_clicked(callback.next)
bprev = Button(axprev, 'Previous')
bprev.on_clicked(callback.prev)

plt.show()

drawing

Examples

Example 1 - example1.py

drawing

Example 2 - example2.py

drawing

Example 3 - Plotting During The Run

Plot live examples in plot_live_1.py, plot_live_2.py and plot_live_3.py.

PLOT_LIVE = True
if PLOT_LIVE:
    fig, _ = plt.subplots(nrows=2, ncols=3, figsize=(12, 6))


def plot(self, graph_dict):
    if PLOT_LIVE:
        ax = self.fig.get_axes()
        for indx, (k, v) in enumerate(graph_dict.items()):
            ax[indx].cla()
            ax[indx].plot(list(range(len(v))), v, c='r')  # , edgecolor='b')
            ax[indx].set_title(f'Plot: {k}')
            ax[indx].set_xlabel('iters')
            ax[indx].set_ylabel(f'{k}')
        plt.pause(0.05)

drawing

Another Option for Life Plotting

from drawnow import drawnow

Tricks

Change figsize in plt mode

You need to plug plt.rcParams["figure.figsize"] = [6.4, 6.4] before plotting.

Credits

About

Basic examples of matplotlib package.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages