Posts about matplotlib

Save Images

Goal

This post aims to introduce how to save images using matplotlib.

Reference

Libraries

In [2]:
import numpy as np
import matplotlib.pyplot as plt

Create a image to save

In [6]:
img = np.random.randint(0, 255, (64, 64))
img
Out[6]:
array([[216, 200, 219, ...,  82, 176, 244],
       [ 17,  90,  86, ...,  91, 234, 195],
       [ 34, 226, 103, ..., 230,  86, 127],
       ...,
       [191, 110,  33, ...,  62, 109,  26],
       [ 43, 238, 208, ...,  51,   0, 123],
       [163, 156, 235, ..., 212, 188,  25]])

Show an image

In [9]:
plt.imshow(img);
plt.axis('off');

Save an image as png

In [33]:
plt.savefig('../images/savefig_sample_image.png')
<Figure size 432x288 with 0 Axes>
In [36]:
!ls ../images | grep image.png
savefig_sample_image.png

XKCD-style Plot using matplotlib

Goal

This post aims to introduce how to plot the data using matplotlib in an XKCD style.

image

Libraries

In [1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

Create data to plot

In [2]:
x = np.linspace(-np.pi, np.pi, 100)
df_data = pd.DataFrame(data={'sin x': np.sin(x), 'cos x': np.cos(x)}, index=x)
df_data.head()
Out[2]:
sin x cos x
-3.141593 -1.224647e-16 -1.000000
-3.078126 -6.342392e-02 -0.997987
-3.014660 -1.265925e-01 -0.991955
-2.951193 -1.892512e-01 -0.981929
-2.887727 -2.511480e-01 -0.967949
In [3]:
df_data.plot(title='Normal Matplotlib Style');
In [4]:
with plt.xkcd():
    df_data.plot(title='XKCD Style');