Create a line chart with axis ticks and legends using Matplotlib

Matplotlib can be an annoying library to learn. Here’s how to create a simple line chart with custom axis ticks and legends.

Here’s the code to do all that (you can do this in a Jupyter notebook):

import matplotlib.pyplot as plt
%matplotlib inline

fig, ax = plt.subplots()

ax.plot(x, y, label='Main thing')

ax.set_title('Hello, matplotlib')
ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')

ax.set_xticks(x)
ax.set_yticks(range(0, 110, 10))

ax.legend()

plt.show()
plt.close()

And here’s what you would see as the output:

Let’s walk through the code

To set custom axis ticks, you need to use plt.subplots instead of plt.figure. The subplots function returns both the figure and the main axis.

Next, we call the plot function on the axis instead of writing plt.plot. This comes in handy when doing subplots, where the axis you call the function on determines which subplot your date is rendered in. The label that you pass here becomes the legend.

if you’ve used the functions plt.xlabel and plt.ylabel to set the x & y label, the corresponding axis functions are ax.set_xlabel and ax.set_ylabel. Similarly, plt.title function becomes ax.set_title.

Finally, you set the axis ticks using ax.set_xticks and ax.set_yticks. Both these functions expect you to pass a list of numbers where you want the tick to appear.

Finally, call the ax.legend function so that it renders the legend. It uses the label that you passed to ax.plot.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Site Footer

Sliding Sidebar