如何绘制多折线图:以月份为X轴、观影量为Y轴展示各电影类型日数据
Hey Jack, let's work through getting that multi-line chart you need. The issue with your current code is that it outputs a multi-indexed Series, which isn't structured properly for direct plotting. Let's break this down step by step:
Step 1: Reshape Your Data into a Plot-Friendly Format
First, we need to group your data by Date and Genre, then pivot it so each genre becomes a column (with dates as the index). This structure makes it trivial to plot each genre as a separate line.
# Group by date + genre, count daily views, then pivot genres to columns daily_genre_counts = df_movies_2018.groupby(['Date', 'Genre']).size().unstack(fill_value=0)
groupby(['Date', 'Genre']).size()counts how many times each genre was watched per day.unstack(fill_value=0)converts the genre index into columns, filling days with no views for a genre with 0 (so we don't have gaps in our lines).
Step 2: Plot the Daily Multi-Line Chart
Now we can use matplotlib to plot each genre's daily view count, with the X-axis formatted to show months (while retaining daily precision in the data):
import matplotlib.pyplot as plt import matplotlib.dates as mdates # Set up the plot canvas fig, ax = plt.subplots(figsize=(12, 6)) # Loop through each genre column and plot its daily counts for genre in daily_genre_counts.columns: ax.plot(daily_genre_counts.index, daily_genre_counts[genre], label=genre) # Format X-axis to show month labels (e.g., Jan, Feb) ax.xaxis.set_major_locator(mdates.MonthLocator()) # Place ticks at the start of each month ax.xaxis.set_major_formatter(mdates.DateFormatter('%b')) # Use 3-letter month names # Add labels and title ax.set_title('Daily Movie View Counts by Genre (2018)') ax.set_xlabel('Month') ax.set_ylabel('Daily View Count') # Add a legend to distinguish genres ax.legend() # Adjust layout to prevent label cutoff plt.tight_layout() plt.show()
Bonus: If You Want Monthly Aggregates Instead
If you actually meant to plot total monthly views per genre (instead of daily), here's how to adjust the data and plot:
# Group by month (using dt.to_period) and genre, then pivot monthly_genre_counts = df_movies_2018.groupby([df_movies_2018['Date'].dt.to_period('M'), 'Genre']).size().unstack(fill_value=0) # Convert period index back to datetime for smooth plotting monthly_genre_counts.index = monthly_genre_counts.index.to_timestamp() # Plot monthly totals fig, ax = plt.subplots(figsize=(10, 5)) for genre in monthly_genre_counts.columns: ax.plot(monthly_genre_counts.index, monthly_genre_counts[genre], marker='o', label=genre) # Format X-axis same as before ax.xaxis.set_major_locator(mdates.MonthLocator()) ax.xaxis.set_major_formatter(mdates.DateFormatter('%b')) ax.set_title('Monthly Movie View Counts by Genre (2018)') ax.set_xlabel('Month') ax.set_ylabel('Total Monthly Views') ax.legend() plt.tight_layout() plt.show()
The core fix here is reshaping your grouped data into a "wide" format where each genre is a column—this lets matplotlib easily map each column to a distinct line on your chart.
内容的提问来源于stack exchange,提问作者JackX

