如何让plt.style作用于Pandas次坐标轴绘图?双图标签合并问题
Fixing Dual-Axis Plot Issues in Matplotlib (Labels + Style Application)
Got it, let's work through your two Matplotlib problems step by step: getting labels on both bar and line plots, and making the fivethirtyeight style apply properly to your secondary y-axis. Here's a revised, working version of your code with explanations:
import matplotlib.pyplot as plt import pandas as pd # Load the fivethirtyeight style FIRST, before creating any plots plt.style.use('fivethirtyeight') # Replace this with your actual totals DataFrame totals = pd.DataFrame({ 'col1': [12, 24, 36], 'col2': [18, 30, 42], 'col3': [8, 16, 24], 'col4': [3, 6, 9] # Example column for the secondary axis line plot }) fig = plt.figure(figsize=(8, 5)) ax = fig.add_subplot(111) # Plot bar chart on primary axis, explicitly set labels for each series bar_plots = totals[['col1', 'col2', 'col3']].plot( kind='bar', ax=ax, label=['Column 1', 'Column 2', 'Column 3'] # Human-readable labels ) plt.xticks(rotation=0) # Create secondary axis and plot line chart ax2 = ax.twinx() # Use the fivethirtyeight color cycle for the line plot to match style color_cycle = plt.rcParams['axes.prop_cycle'].by_key()['color'] line_plot = totals['col4'].plot( kind='line', ax=ax2, color=color_cycle[3], # Pick the 4th color in the style's cycle (avoids bar colors) marker='o', # Add markers for better visibility (matches fivethirtyeight style) label='Column 4 (Line)' ) # Merge legends from both axes for a clean, unified legend handles1, labels1 = ax.get_legend_handles_labels() handles2, labels2 = ax2.get_legend_handles_labels() ax.legend(handles1 + handles2, labels1 + labels2, loc='upper left') # Style the secondary axis to fully match fivethirtyeight ax2.tick_params(axis='y', colors=color_cycle[3]) # Match tick color to line color ax2.set_ylabel('Secondary Axis Value', color=color_cycle[3]) # Match label color ax2.grid(False) # Turn off secondary grid (fivethirtyeight uses primary grid only) plt.tight_layout() plt.show()
Key Fixes & Explanations:
- Style Loading Order: Always load the
fivethirtyeightstyle before creating any plot elements. Twin axes don't inherit style settings automatically, so we manually pull the style's color cycle for the line plot and adjust secondary axis colors to match. - Explicit Labels: We added
labelparameters to both the bar and line plots so Matplotlib can generate proper, readable legends for all series. - Unified Legend: Since each axis has its own default legend, we combine them into one to avoid cluttering the plot.
- Secondary Axis Styling: We matched the line, tick, and label colors to the style's color cycle, and turned off the secondary grid to stay true to
fivethirtyeight's clean, primary-grid-focused look.
内容的提问来源于stack exchange,提问作者J. Doe
相关产品推荐
相关产品推荐

