基于Plotly实现支持X轴滚动的分组柱状图技术求助
Hey there! Let's sort out your grouped bar chart issue—you're right, the code you tried is creating a stacked chart because you're feeding all your data into a single Bar trace. Here's how to fix it, add category-specific colors, and enable X-axis scrolling for all your dates:
Step 1: Preprocess Your Data First
Your raw data has duplicate entries for the same category and date (like two apple entries in 10/2020). We need to aggregate these values first so each date-category pair has one total value. Using pandas' groupby makes this easy:
import pandas as pd # Aggregate values by date and category, fill missing categories with 0 aggregated_df = df.groupby(['date', 'category'])['value'].sum().unstack(fill_value=0)
Step 2: Build the Grouped Bar Chart
To get grouped bars, you need a separate Bar trace for each category. This lets Plotly display them side-by-side instead of stacking. We'll also assign custom colors to each category for clarity:
import plotly.graph_objects as go # Define custom colors for each category (adjust these to your preference) category_colors = { 'apple': '#ff6b6b', 'banana': '#4ecdc4', 'strawberry': '#ffe66d' } # Initialize the figure fig = go.Figure() # Add a trace for each category for category in aggregated_df.columns: fig.add_trace(go.Bar( x=aggregated_df.index, y=aggregated_df[category], name=category, text=category, textposition='auto', marker_color=category_colors.get(category, '#1a535c') # Fallback color if category is new ))
Step 3: Enable X-Axis Scrolling & Final Layout Tweaks
Add a rangeslider to the X-axis so you can scroll through all your dates, and set barmode='group' explicitly to ensure bars are grouped, not stacked:
fig.update_layout( barmode='group', title='Monthly Value by Category', xaxis=dict( title='Month/Year', rangeslider=dict(visible=True), # Turn on the scrollable rangeslider type='category' # Treat dates as categorical values (works for string dates like '10/2020') ), yaxis=dict(title='Total Value') ) # Show the chart fig.show()
Key Notes
- Why separate traces? Plotly only groups bars when each category is its own data series. A single trace will always stack all values together.
- Handling new categories: The fallback color in
marker_colorensures any new categories you add later will still get a consistent color without updating the code. - Date format flexibility: If you switch your dates to a standard date format (e.g., '2020-10'), you can change
xaxis.typeto'date'for more intelligent scrolling (like zooming by month/year).
内容的提问来源于stack exchange,提问作者mlenthusiast

