DEV Community


Better Plots (in Three Lines!)

pj_trainor profile image PJ Trainor ・2 min read

A prettier plot, with just a little more code!

If you've done any plotting in python, you've almost certainly used matplotlib. While it offers a simple approach to making plots, they are sometimes... well they can be a bit ugly, by default.

I'll go over two quick tips to give your plots a little more personality:

  1. Replacing the default styles
  2. Making prettier titles

Note There are plenty of other plotting options with their own styles (seaborn, plotly, bokeh, etc.), but matplotlib is the most widely used, so that's what I'll focus on

You can skip to the below to play around with these styles!

1. Replacing the Default Styles

Next time you type in that import statement, consider adding just one more line:

import matplotlib.pyplot as plt'ggplot')

Now when you make a plot, it will use the styles found in ggplot, a popular plotting library in R.

There are plenty of other options, such as fivethirtyeight and seaborn-colorblind!

Note: If you don't want to apply one style to every plot, you can do:

  plt.plot(x, y)

2. Making Prettier Titles

Matplotlib puts titles in the center, right at the top. Did you know you can move that title around? Did you know that you can have multiple titles? We can use both to make nicer titles:

plt.title("The Main Title", loc='left', fontsize=18)
plt.title("a subtitle", loc='right', fontsize=13, color='grey')

If you have something plotted already, then this moves your main title to the left, and adds a smaller and greyed-out subtitle on the right. It's a great way to give your plots more context, and make them look better!

I'll even leave you with a function that makes this easier to implement:

def fancy_titles(t1, t2, ax=None):
  if ax:
    ax.set_title(t1, loc='left', fontsize=18)
    ax.set_title(t2, loc='right', fontsize=13, color='grey')
    plt.title(t1, loc='left', fontsize=18)
    plt.title(t2, loc='right', fontsize=13, color='grey')

plt.plot(x, y)
fancy_titles("A Cool Title", "a cooler subtitle")

Lastly, here's a, so you can play around with different styles:

Discussion (0)

Forem Open with the Forem app