How to Set Tick Labels in Matplotlib ?

Matplotlib is the widely used open source visualization python library among the data scientist. But one of the most important tasks is how to make your visualization more readable and interpretation among the viewers. Therefore we use tick labels in the figure. In this tutorial of how to, you will know how to set tick labels in Matplotlib. How to add labels to axes and the figure.

Before plotting the figure obviously, you have to import the necessary python libraries lets import them.

How to add labels to the plot?

Adding the labels to the figure except the pie chart is the same. You use the method xlabel() and ylabel() for naming the x and y-axis label. But in the pie figure you have to define the labels a list and then pass it inside the pie() methods. Let look the code.
Addin the label in a bar chart.

x = range(1,10)
y= [10,9,8,7,6,5,4,3,2]
plt.bar(x,y)
# add labels
plt.xlabel("x-axis")
plt.ylabel("y-axis")

Plotting the pie chart with the labels.

values = [10,20,30,50,60]
pie_labels = [ "A","B","C","D","E"]
plt.pie(values,labels=pie_labels)

How to set tick labels in Matplotlib?

In this section, you will learn how to add the set tick labels dynamically. All the code has been done on the dataset of the mtcars you can download it from here. Mtcars Dataset.

Step 1: Read the dataset

cars = pd.read_csv("data/mtcars.csv")
cars.columns = ["car_name", "mpg","cyl","disp ","hp"," drat","wt","qsec","vs","am","gear","carb"]

Step 2: Explore the dataset.

Here exploring means counting the number of records in the dataset. In our example, each column has 32 values.

cars.count()

Step 3: Create figure and add axes

Suppose you want to plot the mpg variable in the figure. Then you have to first create a figure and add axes to the figure. Use the following code.

#create figure
fig = plt.figure()
# add axes to the figure
ax = fig.add_axes([1,1,1.1,1.1])
#plot the figure
mpg = cars["mpg"]
mpg.plot()

Here add_axes() will create axes on the figure and the figure() method will create a figure.

Step 4: Add the labels to the ticks

For adding the ticks you have to first create x ticks for the variable you want to plot. Like in this example for the mpg variable.

# set the x ticks on the axes
ax.set_xticks(range(mpg.count()))

It will create 32 ticks for the mpg variable as is count is 32. After that, you can add the labels for each tick using the set_xticklabels() method.

#set the x ticks labels
ax.set_xticklabels(cars["car_name"],rotation=60)

You can also set the title for the axes using the set_title() method.

# set the axes title
ax.set_title(" Figure for the miles per gallon of each car")

You have successfully plotted the Matplotlib figure with the x ticks labels.