python Matplotlib中重复的分类X轴标注

zpf6vheq  于 2022-12-25  发布在  Python
关注(0)|答案(1)|浏览(151)

我有一个简单的问题:为什么我的x轴标签重复?

以下是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

以下是我尝试过的方法:

agxfikkp

agxfikkp1#

可以使用bax.locator_params(axis='x', nbins=len(compositions))减少x刻度的数量,使其与compositions的长度匹配。
更多关于locator_params()方法的信息,该方法控制主要刻度定位器的行为: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()

结果:

相关问题