Repeated Categorical X-Axis Labels in Matplotlib

Question:

I have a simple question: why are my x-axis labels repeated?

MWE Plot

Here’s an MWE: X-Axis Labels MWE

a = { # DATA -- 'CATEGORY': (VALUE, ERROR) 
      'Cats': (1, 0.105), 
      'Dogs': (2, 0.023), 
      'Pigs': (2.6, 0.134)
     }

compositions = list(a.keys()) # MAKE INTO LIST

a_vals = [i[0] for i in a.values()] # EXTRACT VALUES
a_errors = [i[1] for i in a.values()] # EXTRACT ERRORS

fig = plt.figure(figsize=(8, 6)) # DICTATE FIGURE SIZE   
bax = brokenaxes(ylims=((0,1.5), (1.7, 3)), hspace = 0.05) # BREAK AXES 
bax.plot(compositions, a_vals, marker = 'o') # PLOT DATA

for i in range(0, len(a_errors)): # PLOT ALL ERROR BARS
  bax.errorbar(i, a_vals[i], yerr = a_errors[i], capsize = 5, fmt = 'red') # FORMAT ERROR BAR

Here’s stuff I tried:

Asked By: DarkRunner

||

Answers:

You can use bax.locator_params(axis='x', nbins=len(compositions)) to reduce the number of x-ticks so that it matches the length of compositions.

More on locator_params() method, which controls the behavior of major tick locators:
https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.locator_params.html

import matplotlib.pyplot as plt
from brokenaxes import brokenaxes

a = {  # DATA -- 'CATEGORY': (VALUE, ERROR)
    'Cats': (1, 0.105),
    'Dogs': (2, 0.023),
    'Pigs': (2.6, 0.134)
}

compositions = list(a.keys())  # MAKE INTO LIST

a_vals = [i[0] for i in a.values()]  # EXTRACT VALUES
a_errors = [i[1] for i in a.values()]  # EXTRACT ERRORS

fig = plt.figure(figsize=(8, 6))  # DICTATE FIGURE SIZE
bax = brokenaxes(ylims=((0, 1.5), (1.7, 3)), hspace=0.05)  # BREAK AXES
bax.plot(compositions, a_vals, marker='o')  # PLOT DATA

for i in range(0, len(a_errors)):  # PLOT ALL ERROR BARS
    bax.errorbar(i, a_vals[i], yerr=a_errors[i], capsize=5, fmt='red')  # FORMAT ERROR BAR
    
bax.locator_params(axis='x', nbins=len(compositions))

plt.show()

Result:

enter image description here

Answered By: コリン
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.