Home > Software design >  Why aren't all ticklabels shown on the x-axis?
Why aren't all ticklabels shown on the x-axis?

Time:02-27

This is my code.

fig, ax1 = plt.subplots() 
fig.set_figheight(7)
fig.set_figwidth(12)
ax1.bar(df.index, df['occurence of defects'], color="C0")
ax1.set_ylabel("Qty", color="C0")
ax1.tick_params(axis="y", colors="C0")
ax1.set_xlabel("Defect")
ax1.set_xticklabels(df['Name of Defect'],rotation=45)
ax2 = ax1.twinx()
ax2.plot(df.index, df["cum percentage"], color="C1", marker="D", ms=7)
ax2.yaxis.set_major_formatter(PercentFormatter())
ax2.tick_params(axis="y", colors="C1")
plt.show()

this is ss of output enter image description here I made circles where labels are missing. How can I fix that? Even the current labels on the x-axis aren't in their supposed positions.

CodePudding user response:

I don't know the details, but it automatically determines the scale of the graph according to the number of ticks. In this case, we are skipping one. Try disabling #ax1.set_xticklabels(df['Name of Defect'],rotation=45) and you will understand. If you specify the number of ticks for the axis you need, it will match the label and display.

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
import numpy as np

df = pd.DataFrame({'Name of Defect':list('ABCDEFGHIJKLMNOP'), 'occurence of defects':np.random.randint(1,10,16)})

df['cum'] = df['occurence of defects'].cumsum()
df.sort_values('occurence of defects', ascending=False, ignore_index=True, inplace=True)
df['per'] = df['cum'].apply(lambda x: x / df['cum'].sum())
df['cum percentage'] = df['per'].cumsum()

fig, ax1 = plt.subplots() 
fig.set_figheight(7)
fig.set_figwidth(12)
ax1.bar(df.index, df['occurence of defects'], color="C0")
ax1.set_ylabel("Qty", color="C0")
ax1.tick_params(axis="y", colors="C0")
ax1.set_xlabel("Defect")
ax1.set_xticks(np.arange(0,16))
ax1.set_xticklabels(df['Name of Defect'],rotation=45)
ax2 = ax1.twinx()
ax2.plot(df.index, df["cum percentage"], color="C1", marker="D", ms=7)
ax2.yaxis.set_major_formatter(PercentFormatter())
ax2.tick_params(axis="y", colors="C1")
plt.show()

enter image description here

CodePudding user response:

Matplotlib has such a characteristics, that when you invoke set_xticklabels, then set_xticks should also be invoked (to specify where these labels are to be placed (at which x coordinates)).

In your case x labels should be placed below each bar, so insert:

ax1.set_xticks(df.index)

before:

ax1.set_xticklabels(df['Name of Defect'], rotation=45)

The reason is that quite often x labels should be placed not at each x coordinate, especially when the plot type is other than bar.

And another hint: Since your x labels are quite long, consider rotation of 90, or other, but greater than 45.

  • Related