使用brokenaxis()时x轴刻度标签偏移且缺失的问题求助
I totally get your frustration—when using brokenaxes, the x-tick labels don’t behave like they do with regular Matplotlib axes, which is why you’re only seeing 5 labels with the first one missing. Here’s how to fix this and get all 9 labels to display exactly like your unbroken plot:
The Root Cause
brokenaxes creates multiple sub-axes under the hood instead of a single axis. By default, only the bottom sub-axis shows x-ticks, and it auto-adjusts the tick count, leading to missing or truncated labels. To fix this, you need to explicitly configure each sub-axis to use your full set of ticks and labels.
Solution Code
Here’s your modified plotting code that retains all x-tick labels matching your original unbroken plot:
import numpy as np import pandas as pd import matplotlib.pyplot as plt from brokenaxes import brokenaxes # Computing dataframe (unchanged from your code) column1 = np.array(('Grünland','KA','MA','SG','SW','WG','WR','WW','ZR')) column2 = np.array((1332.9,-429.7,-6041.6,-686.5,-72.4,-37.5,-4224.6,-4208.8,-3955.8)) column3 = np.array((1332.9,42.7,-1018.7,-32.7,21.7,-327.2,-3117.4,-15431.5,206.2)) data1 = np.column_stack((column1,column2,column3)) data = pd.DataFrame(data1,columns=['Frucht','SUM19','SUM20']) data['SUM19'] = pd.to_numeric(data['SUM19']) data['SUM20'] = pd.to_numeric(data['SUM20']) labels = data['Frucht'] x = np.arange(len(labels)) # the label locations width = 0.35 # the width of the bars # Plot with broken y-axis (modified part) fig = plt.figure() bax = brokenaxes(ylims=((-16000,-15000), (-6500, 1500)), hspace=.05) rects1 = bax.bar(x - width/2, data['SUM19'], width, label='2019') rects2 = bax.bar(x + width/2, data['SUM20'], width, label='2020') # Configure x-ticks for all sub-axes for ax in bax.axes: # Set exact tick positions and your custom labels ax.set_xticks(x) ax.set_xticklabels(labels) # Expand x-axis limits to prevent label cutoff ax.set_xlim(-0.5, len(x) - 0.5) # Hide labels on upper sub-axes to avoid duplicate text if ax != bax.axes[-1]: ax.tick_params(labelbottom=False) plt.legend() plt.show()
Key Changes Explained
- Iterate over all sub-axes:
bax.axesgives you access to every axis created bybrokenaxes. Setting ticks and labels for each ensures alignment across the broken plot. - Set x-axis limits:
ax.set_xlim(-0.5, len(x)-0.5)makes sure the first and last labels aren’t cut off by the plot edges. - Hide duplicate labels: We only keep labels on the bottom sub-axis (
bax.axes[-1]) to avoid overlapping text on upper axes while keeping ticks aligned.
This should make your broken-axis plot’s x-tick labels match exactly with your original unbroken plot!
内容的提问来源于stack exchange,提问作者user13897961

