Matplotlib discrete note

Last modified 4 years ago / Edit on Github
Danger icon
The last modifications of this post were around 4 years ago, some information may be outdated!

Import library

import matplotlib.pyplot as plt
import numpy as np

Generate colors based on list

We wanna generate a list of colors automatically based on the elements in some list (the idea from popai),

def get_colors(list_vals, list_colors=["#fb4747", "#315ace", "#b5f6e5", "#FFB347"]):
dict_colors = polylinear_gradient(list_colors, n=len(list_vals))
dict_colors_ok = {}
for i, val in enumerate(list_vals):
dict_colors_ok[val] = dict_colors['hex'][i]

return dict_colors_ok


Axes' options,

# Hide the axis
# and 'on' to display it again
# Set the limit
plt.xlim(0, 3.5)
plt.ylim(0, 3.5)
# Axes' label
plt.xlabel('students', fontsize=14)
# axes' tick size & rotation
plt.xticks(fontsize=14, rotation=90)
plt.yticks(fontsize=14, rotation=90)
# range of ticks
plt.xticks(np.arange(0., 1., step=0.01))
plt.yticks(np.arange(0., 1., step=0.01))

Set equal 2 axes[ref],

# get the current axes and apply the function


Check the official doc for more information.

# default for all
matplotlib.rcParams['figure.figsize'] = (20,5)
plt.plot(X, y, 'ro') # red and 'o' points
# set figure size
plt.figure(figsize=(20, 5))
plt.figure(figsize=(20, 5), dpi= 60)
# rotate z label
plt.xticks(rotation=90, fontsize=10)
# linestyle and marker
plt.plot(marker='.', ls='') # scatter plot
plt.plot(X, '.', markersize=15, linewidth=2)

Plot directly with dataframe,

👉 Check more in official doc.

df.plot(figsize=(20, 5))
# different types
df.plot(style=['r.', 'bx']) # 2 features
# add x,y labels
plt.xlabel('features', fontsize=14)
plt.ylabel('% of nans', fontsize=14)
# rotate x ticks
df.plot(kind='bar', rot=90)


# from the plots
plt.plot(x, np.sin(x), '-b', label='Sine')
plt.plot(x, np.cos(x), '--r', label='Cosine')
# custom: independent from the plots
from matplotlib.lines import Line2D
plt.legend([Line2D([0], [0], color='b'), Line2D([0], [0], color='r')], ['blue', 'red'])

Legend from list of colors

Suppose we have a list of group with different colors. We wanna make legends for them,

# generate auto the colors based on list lst_clusters (see previous section)
dict_colors = get_colors(lst_clusters)

[Line2D([0], [0], color=dict_colors[key]) for key in dict_colors],
loc='lower center',
bbox_to_anchor=(.5, 1.),
prop={'size': 15}

Legend from list of colors


Plot from a list of true/false (ref to an example of Bernoulli distribution)

image = # np.array(4, 4) of random True/False
plt.imshow(image, cmap='gray') # plot


For example, we wanna create a 4x4 plots[ref],

plt.figure(figsize=(12, 10), dpi= 60)
for i in range(4):
pos = i+1
plt.title('title_'+str(pos), fontsize=18)

Using ax,

size = len(list_features)
f, axs = plt.subplots(int((size+1)/2), 2, figsize=(15,15/5*int(size/2 + 1/2)))
for ax, feat in zip(axs.ravel(), list_features):
df_feat = df[feat]
for idt, df_id in df_feat.groupby('batch_id'):
ax.plot(x, y, color='royalblue', alpha=0.5)

Fill between range

plt.fill_between(df.index, df["yhat_lower"], df["yhat_upper"], color='#0072B2', alpha=0.2)

Plot a photo (imshow)

With grayscale and misc

from scipy import misc

img = misc.face(gray=True)
plt.imshow(img, cmap='gray', vmin=0, vmax=255)

With grayscale and custom file

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

fname = 'image.png'
image ="L")
# If you have an L mode image, that means it is a single channel image - normally
# interpreted as greyscale. The L means that is just stores the Luminance.
# It is very compact, but only stores a greyscale, not colour.

arr = np.asarray(image)
plt.imshow(arr, cmap='gray', vmin=0, vmax=255)
# ERR: Clipping input data to the valid range for
# imshow with RGB data ([0..1] for floats or [0..255] for integers)

Save figure to file

Using plt.savefig()

To be sure that plt.savefig()[ref] comes before In the case you wanna use any time you want, just call plt.gcf() to "get current figure" first. For example,[ref]

fig1 = plt.gcf() # get the current figure # show the plot
fig1.savefig('test.png', dpi=100)

Remark: There are the axes inside the exported photo (all are printed on notebook)!!

Using imageio

They export only the photo.

import imageio
# img = misc.face(gray=True)
# or
# img = np.asarray('abc.jpg').convert("L"))
imageio.imwrite('filename.jpg', img) # save the file
# ERR: Lossy conversion from float64 to uint8. Range […,…].
# Convert image to uint8 prior to saving to suppress this warning
imageio.imwrite('filename.jpg', img.astype(np.uint8))

💬 Comments

Support Thi Support Thi