What's the point of set_xticklabels?

I don’t understand why we need to go through the whole process of setting set_xticks and then set_xticklabels when we can simply just use the string labels we have already.

from matplotlib import pyplot as plt drinks = ["cappuccino", "latte", "chai", "americano", "mocha", "espresso"] sales = [91, 76, 56, 66, 52, 27] # We can create simple car charts plt.bar(drinks, sales) plt.show()

In the above example, this works just fine! We get a chart with the names of the drinks on the x-axis and the sales numbers on the y-axis. But in the exercise, you are made to first give the x-axis numerical values i.e range(len(drinks)) and then set the xticklabels to the names of the drinks. Why must we do this? Seems a bit unnecessary…

Here are the links to the exercises:

Here’s the link to the exercises:

https://www.codecademy.com/courses/data-visualization-python/lessons/matplotlib-ii/exercises/simple-bar-chart
https://www.codecademy.com/courses/data-visualization-python/lessons/matplotlib-ii/exercises/basic-bar-chart-ii

Do you have a link to the exercise? At a guess it’s because you can’t guarantee the size of the figure or the number of ticks generated (if you used a different sized screen for example you might have more or less ticks). You’ll see this more notably in graphs other than bar charts or those with non-linear axes.

There are rules about how ticks are generated but they’re quite complicated. If you definitely need x labels it’s probably simpler and more robust to set the ticks yourself.

So in short the example just doesn’t cover many options and may fail unexpectedly.

2 Likes

Here’s the link to the exercises:

https://www.codecademy.com/courses/data-visualization-python/lessons/matplotlib-ii/exercises/simple-bar-chart
https://www.codecademy.com/courses/data-visualization-python/lessons/matplotlib-ii/exercises/basic-bar-chart-ii

1 Like

Also adding to this, depending on the pathway you are currently on, you may go through the Seaborn library instead, which greatly simplifies all things, including x-ticks, their labelling etc.

1 Like

Seaborn is a useful module and can often take a lot of the work out of your hands. You will however have more power over the figure if you use the underlying matplotlib tools (seaborn is a wrapper on top of matplotlib). There’s a time and a place for both of them.

My apologies to @babasariffodeen as I apparently overlooked a reply. The following thread might be of interest to you (or since it’s a bit late perhaps any other viewer) where the value of ticks affects their location in a negative way: Netflix Data Capstone.

The fourth post in particular shows an image of what can happen if you’re not dealing with fixed locations. Many times you don’t need to worry about this and matplotlib will try to place labels for you but it is worth knowing the general basis for how tick placement works.