使用Matplotlib绘制Revenue柱状图不符合预期,寻求解决方案
Fixing Your Revenue Bar Chart with Matplotlib
Let's break down what's going wrong with your current code and how to adjust it to match your expected chart style:
Issues with Your Current Code
- Incorrect bar width: Setting
width=30when your index is datetime-based means each bar spans 30 days, which causes overlapping and the squished, unreadable look you're seeing. - Subplot layout: Your
subplot2gridsetup withrowspan=2in a (6,7) grid combined with a tallfigsize=(10,15)stretches the bars vertically in an unnatural way. - Unformatted x-axis: Without proper date formatting, the x-axis labels become messy and unparseable.
Corrected Code
First, ensure your DataFrame index is properly parsed as datetime (skip this step if it's already a datetime type):
import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates # Convert index to datetime if needed df.index = pd.to_datetime(df.index) # Adjust figure size and subplot layout for better proportions fig = plt.figure(figsize=(12, 6)) ax1 = plt.subplot2grid((1,1), (0,0)) # Simplify to a single subplot for clarity # Plot bars with appropriate width (matches daily interval here) ax1.bar(df.index, df['revenue'], width=0.8, label='Revenue', align='center') # Format x-axis dates to be readable ax1.xaxis.set_major_locator(mdates.MonthLocator()) # Show monthly tick markers ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) # Format labels as Year-Month plt.xticks(rotation=45) # Rotate labels to prevent overlap # Add labels and legend for clarity ax1.set_xlabel('Date') ax1.set_ylabel('Revenue') ax1.set_title('Revenue Over Time') ax1.legend() plt.tight_layout() # Adjust layout to fit all labels and elements plt.show()
Key Adjustments Explained
- Bar width:
width=0.8works well for daily data (adjust to 25-28 if you want monthly bars, matching the average number of days in a month). - Subplot layout: Using a simple 1x1 grid removes unnecessary vertical stretching, making the bars look natural and proportional.
- Date formatting:
MonthLocatorandDateFormatterclean up the x-axis, and rotating ticks ensures labels don't overlap and are easy to read. - Layout adjustment:
tight_layout()ensures all labels, titles, and chart elements fit properly within the figure boundaries.
If your data is aggregated by month instead of day, you can simplify further by plotting against month names/values directly instead of datetime indexes, but the above code works seamlessly for both daily and monthly datetime-indexed data.
内容的提问来源于stack exchange,提问作者Duong Bui
相关产品推荐
相关产品推荐

