使用Python Plotly绘制堆叠图求助:时间轴与动态系列问题
Got it, let's solve this problem step by step. The key challenge here is handling the variable series (s1, s2, etc.) across different time points—we need to first restructure your data into a format Plotly can work with, then create the stacked chart.
Step 1: Restructure the Raw Data
First, we'll convert your tuple-based data into a pandas DataFrame where each row represents a time point, and each column is a series (with 0 values for series that aren't present at that time). This ensures all time points have the same set of series, which is required for stacked charts.
Here's the code to do that:
import pandas as pd import plotly.express as px # Your raw data raw_data = [ ('2018-04-09', '10:18:11',['s1',10],['s2',15],['s3',5]), ('2018-04-09', '10:20:11',['s4',8],['s2',20],['s1',10]), ('2018-04-10', '10:30:11',['s4',10],['s5',6],['s6',3]) ] # Process each entry into a dictionary with datetime and series values processed_entries = [] for entry in raw_data: # Combine date and time into a single datetime object datetime_obj = pd.to_datetime(f"{entry[0]} {entry[1]}") entry_dict = {"datetime": datetime_obj} # Add each series and its value to the dictionary for series in entry[2:]: series_name, value = series entry_dict[series_name] = value processed_entries.append(entry_dict) # Convert to DataFrame df = pd.DataFrame(processed_entries) # Get all unique series names across all time points all_series = list({key for entry in processed_entries for key in entry if key != "datetime"}) # Reindex to include all series, filling missing values with 0 df = df.set_index("datetime").reindex(columns=all_series, fill_value=0).reset_index()
Step 2: Create the Stacked Chart
Now that we have a clean DataFrame, we can use Plotly Express to create either a stacked bar chart or a stacked area chart.
Option 1: Stacked Bar Chart
fig = px.bar( df, x="datetime", y=all_series, barmode="stack", labels={"datetime": "Time", "value": "Value"}, title="Stacked Series Over Time (Bar Chart)" ) # Format the x-axis to show your desired time format fig.update_layout( xaxis=dict( tickformat="%H:%M, %Y年%m月%d日" # Example: "10:18, 2018年04月09日" ) ) fig.show()
Option 2: Stacked Area Chart
If you prefer an area chart instead, use this code:
fig = px.area( df, x="datetime", y=all_series, labels={"datetime": "Time", "value": "Value"}, title="Stacked Series Over Time (Area Chart)" ) # Format x-axis fig.update_layout( xaxis=dict( tickformat="%H:%M, %Y年%m月%d日" ) ) fig.show()
Key Notes:
- The
reindexstep ensures every time point has all possible series, filling missing values with 0. This is critical for Plotly to render the stacked chart correctly. - You can adjust the
tickformatstring to match your preferred date/time format. Check pandas' strftime documentation for more format options. - If you need to sort the series in a specific order, just reorder the
all_serieslist before creating the chart.
内容的提问来源于stack exchange,提问作者somerandomguy

