Python柱状图优化:数值保留两位小数及居中显示问题求助
Fixing Decimal Places and Centering Labels on Your Bar Chart
Let's work through your two bar chart issues step by step:
1. Displaying Values with 2 Decimal Places
The pd.options.display.float_format setting only affects how pandas prints DataFrames—it doesn't control the text you add to your matplotlib chart. To fix this, you need to explicitly format each number when passing it to plt.text using string formatting syntax.
2. Centering Labels Above Bars
Your current code adds two separate sets of text (one for total spaces, one for percentages) which can overlap or misalign. We'll adjust the position of each label to sit cleanly above the bar, and lock in center alignment for both.
Updated Working Code
import pandas as pd import matplotlib.pyplot as plt # Your original pivot table logic active_parking = pd.pivot_table( parking[parking['Bldg Status'] == 'ACTIVE'], index='Owned/Leased', values='Total Parking Spaces', aggfunc='mean' ) active_parking['% of Total'] = ((active_parking['Total Parking Spaces'] / active_parking['Total Parking Spaces'].sum()) * 100) print(active_parking, '\n') # Create bar chart and get axis reference ax = active_parking.plot(kind='bar') plt.xticks(rotation=0) # Add formatted, centered labels for Total Parking Spaces for i, number in enumerate(active_parking['Total Parking Spaces']): plt.text( x=i, y=number + 1.5, # Small offset to position text above the bar s=f"{number:.2f}", # Format to 2 decimal places horizontalalignment='center', weight='bold' ) # Add formatted percentage labels (adjust y-offset to avoid overlap) for i, percent in enumerate(active_parking['% of Total']): plt.text( x=i, y=number + 3.5, # Further offset to sit above the total value s=f"{percent:.2f}%", # Format percentage and add % symbol horizontalalignment='center', weight='bold', color='darkgray' ) plt.show()
Key Changes Explained
- Decimal Formatting: Used
f"{number:.2f}"to directly format each value to 2 decimal places in theplt.textcall. This bypasses pandas display settings because we're creating a formatted string explicitly. - Centered Alignment: Kept
horizontalalignment='center'and added small positive offsets to theyparameter (likey=number +1.5) so text sits above the bar instead of overlapping its top edge. - Clean Percentage Placement: Shifted percentage labels further up and used a gray color to distinguish them from total space values, ensuring both sets of labels stay centered and readable.
Expected Chart Output
Your bar chart will now show:
- For LEASED:
44.71(and37.55%if you keep the percentage labels) - For OWNED:
74.37(and62.45%if you keep the percentage labels)
All labels will be neatly centered above their respective bars.
内容的提问来源于stack exchange,提问作者MarkS
相关产品推荐
相关产品推荐

