DEV Community

Cover image for Spicy plots with matplotlib
Bence Kotis
Bence Kotis

Posted on

Spicy plots with matplotlib

The full code used in this article in the form of a Jupyter notebook can be found here.

1. Use Google Fonts!

Google Fonts has thousands of fonts you can download to make your plots look a bit more refined.

The easiest way to install new fonts if you are on Linux is using font-manager.

On Debian or Ubuntu, you can install font-manager by doing:

sudo apt install font-manager

Find your favorite font on Google Fonts.

My current favorite on there would have to be Roboto Condensed. Download and unzip your fonts, then add them(all the .tff files) inside font-manager by clicking the + button on the top left corner:

Alt Text

Now if you open up a Jupyter notebook, you should be able to list all the fonts available to Matplotlib by doing:

#clear the matplotlib font cache (this is important!!!)
!rm -fr ~/.cache/matplotlib

#originally from: http://jonathansoma.com/lede/data-studio/matplotlib/list-all-fonts-available-in-matplotlib-plus-samples/
import matplotlib.font_manager
from IPython.core.display import HTML

def make_html(fontname):
    return "<p>{font}: <span style='font-family:{font}; font-size: 24px;'>{font}</p>".format(font=fontname)

code = "\n".join([make_html(font) for font in sorted(set([f.name for f in matplotlib.font_manager.fontManager.ttflist]))])
HTML("<div style='column-count: 2;'>{}</div>".format(code))

After that, your new fonts should be ready for use by using the fontname attribute in most matplotlib objects, like plt.title:

Alt Text

2. Use gifs/images to add some personality to your plots

Alt Text

This plot looks about as boring as it gets.

Lets write some code to create an image/gif overlay for our plot:

def add_overlay(base_im, overlay_im, newsize, pos, outname='output.gif'):
    '''Adds a png or gif to your plot'''

    #open both images
    original_image = Image.open(base_im)
    animated_gif = Image.open(overlay_im)

    frames = [] #used to store output frames for gif

    #iterate over input gif
    for frame in ImageSequence.Iterator(animated_gif):

        #resize each frame
        frame = frame.resize(newsize) 
        #copy plot and paste gif frame on top
        original_image = original_image.copy()
        original_image.paste(frame, pos)
        frames.append(original_image)

    #you can change the duration variable to change gif speed
    frames[0].save(outname, save_all=True, append_images=frames[1:], duration=70,loop=0)

After adding some images, the plot is a lot more eye-catching!
Alt Text

The same code can be used to add animated gifs to your plot.

Gifs are a great way to annotate your plots and convey how you feel about your results:

Alt Text

Alt Text

Conclusion

I hope these tips gave you a bit of inspiration to spice up your plotting workflow. For the full code used in this article, refer to this Jupyter notebook.

Top comments (0)