请求创建日班次产量并列可视化图表(附Pandas数据集)
Got it, let's build that side-by-side shift production chart you're looking for. Your dataset is already structured perfectly in a Pandas DataFrame, so we can jump straight into plotting with either Matplotlib or Seaborn—both work great for this use case.
Option 1: Matplotlib (Full Control Over Layout)
First, import the necessary libraries, then we'll create grouped bar charts where each day has 3 side-by-side bars (one per shift):
import pandas as pd import matplotlib.pyplot as plt # Your existing data and DataFrame setup x = [{'day' : 1, 'shift' : 1, 'count':3}, {'day' : 1, 'shift' : 2, 'count':5}, {'day' : 1, 'shift' : 3, 'count':7}, {'day' : 2, 'shift' : 1, 'count':2}, {'day' : 2, 'shift' : 2, 'count':4}, {'day' : 2, 'shift' : 3, 'count':6}] x_df = pd.DataFrame(x) x_df = x_df[['day', 'shift', 'count']] # Set up plot parameters days = x_df['day'].unique() num_shifts = x_df['shift'].nunique() bar_width = 0.25 x_pos = range(len(days)) # Create bars for each shift plt.figure(figsize=(8,5)) for shift in range(1, num_shifts+1): shift_data = x_df[x_df['shift'] == shift]['count'] plt.bar([pos + bar_width*(shift-1) for pos in x_pos], shift_data, width=bar_width, label=f'Shift {shift}') # Customize the plot plt.xlabel('Day') plt.ylabel('Production Count') plt.title('Daily Production by Shift') plt.xticks([pos + bar_width for pos in x_pos], days) plt.legend() plt.tight_layout() plt.show()
This code positions each shift's bar next to the others for the same day, uses distinct colors for each shift, and adds clear labels so you can easily compare production across shifts per day.
Option 2: Seaborn (Simpler, Less Code)
If you prefer a more concise approach, Seaborn's catplot does the heavy lifting for grouped bars automatically:
import seaborn as sns import matplotlib.pyplot as plt # Reusing your x_df DataFrame here sns.catplot( data=x_df, x='day', y='count', hue='shift', kind='bar', palette='viridis', height=5, aspect=1.5 ) plt.xlabel('Day') plt.ylabel('Production Count') plt.title('Daily Production by Shift') plt.show()
The hue='shift' parameter is what tells Seaborn to group bars by shift within each day. This gives you a clean, ready-to-use chart without manually calculating bar positions.
Either of these methods will give you the side-by-side comparison you're looking for—pick whichever fits your workflow better!
内容的提问来源于stack exchange,提问作者bryan.blackbee

