Skip to Content
Learn
Line Graphs in Matplotlib
Modify Ticks

In all of our previous exercises, our commands have started with plt.. In order to modify tick marks, we’ll have to try something a little bit different.

Because our plots can have multiple subplots, we have to specify which one we want to modify. In order to do that, we call plt.subplot() in a different way.

ax = plt.subplot(1, 1, 1)

ax is an axes object, and it lets us modify the axes belonging to a specific subplot. Even if we only have one subplot, when we want to modify the ticks, we will need to start by calling either ax = plt.subplot(1, 1, 1) or ax = plt.subplot() in order to get our axes object.

Suppose we wanted to set our x-ticks to be at 1, 2, and 4. We would use the following code:

ax = plt.subplot() plt.plot([0, 1, 2, 3, 4], [0, 1, 4, 9, 16]) plt.plot([0, 1, 2, 3, 4], [0, 1, 8, 27, 64]) ax.set_xticks([1, 2, 4])

Our result would look like this:

tick_marks

We can also modify the y-ticks by using ax.set_yticks().

When we change the x-ticks, their labels automatically change to match. But, if we want special labels (such as strings), we can use the command ax.set_xticklabels() or ax.set_yticklabels(). For example, we might want to have a y-axis with ticks at 0.1, 0.6, and 0.8, but label them 10%, 60%, and 80%, respectively. To do this, we use the following commands:

ax = plt.subplot() plt.plot([1, 3, 3.5], [0.1, 0.6, 0.8], 'o') ax.set_yticks([0.1, 0.6, 0.8]) ax.set_yticklabels(['10%', '60%', '80%'])

This would result in this y-axis labeling:

y_ticks

Now, let’s practice with tick marks.

Instructions

1.

Let’s imagine we are working for a company called Dinnersaur, that delivers dinners to people who don’t want to cook. Dinnersaur recently started a new service that is subscription-based, where users sign up for a whole year of meals, instead of buying meals on-demand.

We have plotted a line for you in the editor representing the proportion of users who have switched over to this new service since it was rolled out in January. First, save the set of axes in a variable called ax. We will use ax to set the x- and y-ticks and labels to make this graph easier to read.

2.

Using ax, set the x-ticks to be the months list.

3.

Set the x-tick labels to be the month_names list.

4.

Set the y-ticks to be [0.10, 0.25, 0.5, 0.75].

5.

Label the y-ticks to be the percentages that correspond to the values [0.10, 0.25, 0.5, 0.75], instead of decimals.

Folder Icon

Sign up to start coding

Already have an account?