Pandas技术求助:如何绘制按Price排序的Top 20 Sire柱状图?
Hey there! Since you're new to Pandas, let's break this down clearly to get you the exact plot you need. The issue with your current code is that it calculates totals for all Sires first, then plots everything—we need to filter down to the top 20 highest total Price Sires before plotting.
Step 1: Calculate Total Price per Sire & Filter Top 20
First, we'll group the data by Sire, sum up their Price values, then grab the top 20 entries sorted by total Price. You can do this in one clean line with nlargest():
# Compute total Price for each Sire, then get the top 20 top_20_sires = df.groupby('Sire')['Price'].sum().nlargest(20)
Alternatively, if you prefer to explicitly sort first (great for understanding the flow):
# Group, sum, sort descending, take top 20 top_20_sires = df.groupby('Sire')['Price'].sum().sort_values(ascending=False).head(20)
Step 2: Plot the Top 20 Sires
Now that we have our filtered dataset, plotting is straightforward. We'll use Pandas' built-in plotting with matplotlib to make it readable:
import matplotlib.pyplot as plt # Create the bar plot top_20_sires.plot( kind='bar', figsize=(12, 6), # Adjust size for readability title='Top 20 Sires by Total Price', color='#2ecc71' # Optional: add a custom color ) # Add labels and tweak formatting to avoid overlapping text plt.xlabel('Sire Name') plt.ylabel('Total Price') plt.xticks(rotation=45, ha='right') # Rotate x-axis labels plt.tight_layout() # Adjust layout to fit labels plt.show()
Quick Note: If You Meant Top 20 Individual Price Entries
If your original nlargest(20, 'Price') was meant to show the top 20 single highest Price records (not total per Sire), here's how to plot those (note: this may show duplicate Sires if they have multiple high-priced entries):
# Get top 20 individual records by Price top_20_records = df.nlargest(20, 'Price')[['Sire', 'Price']] # Plot with Sire as the x-axis top_20_records.plot( kind='bar', x='Sire', y='Price', figsize=(12, 6), title='Top 20 Individual Entries by Price' ) plt.xticks(rotation=45, ha='right') plt.tight_layout() plt.show()
That should give you exactly the visualization you need. Let me know if you run into any snags!
内容的提问来源于stack exchange,提问作者Leonie

