So steuern Sie die Zorder-Werte auf überlagerten Balken in einem Histogrammdiagramm in MatplotlibPython

Python-Programme
Anonymous
 So steuern Sie die Zorder-Werte auf überlagerten Balken in einem Histogrammdiagramm in Matplotlib

Post by Anonymous »

Ich habe eine Liste mit drei Datenrahmen, von denen jeder vier interessante Spalten enthält. Ich möchte eine Figur mit vier Unterhandlungen erstellen (eine für jede Spalte). In jedem Unterplot möchte ich zunächst ein überlagertes Histogramm aus drei Datenrahmen erstellen, d. h. an jedem Bin-Index gibt es drei Balken oder Zählungen für drei Datenrahmen. Hier möchte ich die Zorder so zuweisen, dass bei jedem Bin-Index die höchste Anzahl zuerst und die niedrigeren angezeigt werden. Aber das bekomme ich auch nicht hin, nachdem ich die iterative Zorder verwendet habe. Bitte helfen Sie mir, meinen Code zu verstehen und zu korrigieren.

Code: Select all

# Helper function to clean data
def clean_series(series):
return series.dropna().replace([np.inf, -np.inf], np.nan).dropna()

fig, axs = plt.subplots(2, 2, figsize=(8, 6), dpi=120,
gridspec_kw={'hspace': 0.40, 'wspace': 0.15})
axs = axs.flatten()

colors = ['blue', 'darkorange', 'darkolivegreen']
airmass = ['Marine', 'Combined', 'Continental']
# each df represent the airmass
datalist = [df1, df2, df3]

# Variables with enhanced formatting
variables = [
('col1', 'CDNC', (-150, 850), (0, 20), (np.arange(0,21,5)), 50),
('col2', 'LWC', (-0.09, 0.8), (0, 50), (np.arange(0,51,10)), 30),
('col3', 'ED', (5, 20), (0, 30), (np.arange(0,31,5)), 30),
('col4', 'MVD', (5, 20), (0, 35), (np.arange(0,36,5)), 30)]

# First loop through the variables
for plot_idx, (col_name, xlabel, xlim, ylim, yticks, n_bins) in enumerate(variables):
ax = axs[plot_idx]

# Grid - MUST be plotted first and set below
ax.set_axisbelow(True)
ax.grid(True, axis='both', which='major', linestyle='--',
linewidth=0.3, alpha=0.4, zorder=0, color='gray')

# Store histogram data for all three dataframes first
hist_data = []
for i, df in enumerate(datalist):
# i is actually the airmass index
data = clean_series(df[col_name])
if len(data) > 0:
# Calculate histogram values without plotting yet
counts, bins = np.histogram(data, bins=n_bins, range=xlim,
weights=np.ones(len(data)) / len(data) * 100)
hist_data.append((i, data, counts, bins))

# For each bin, sort by height and plot the largest first
if hist_data:
n_bins_actual = len(hist_data[0][2]) # actually the number of bars
bins_edges = hist_data[0][3] # bin edge value

# loop through the number of bars
for bin_idx in range(n_bins_actual):
bin_heights = [(hist_data[j][0], hist_data[j][2][bin_idx])
for j in range(len(hist_data))]
# Sort by height (descending order: largest first)
bin_heights.sort(key=lambda x: x[1], reverse=True)

# Plot bars for this bin with INCREASING zorder (largest gets lowest zorder)
for zorder_increment, (airmass_idx, height) in enumerate(bin_heights):
if height > 0:  # Only plot if there's data
ax.bar(bins_edges[bin_idx], height,
width=bins_edges[1] - bins_edges[0],
alpha=0.35, color=colors[airmass_idx],
edgecolor=colors[airmass_idx], linewidth=0,
align='edge', zorder=10 + zorder_increment)

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post