基于Plotly的Python自定义堆叠条形图绘制技术问询
No worries, let's walk through turning your sample data into a clean stacked bar chart with Plotly. First, we need to restructure your nested tuple/list data into a format that Plotly can easily work with—pandas DataFrames are perfect for this, as they align data neatly for visualization.
Step 1: Install & Import Required Libraries
First, make sure you have the necessary packages installed (run pip install plotly pandas if you haven't already). Then import them:
import plotly.express as px import pandas as pd
Step 2: Flatten Your Raw Data
Your original data groups multiple product-value pairs under a single date-time entry. We need to flatten this so each product-value pair gets its own row, tied to the correct date and time:
# Your original sample data data = [ ('2018-04-17','22:00:00',['p1',5],['p2',10],['p3',15]), ('2018-04-18','20:00:00',['p3',5],['p4',10],['p3',15]) ] # Convert to a flat, structured format flattened_entries = [] for entry in data: date, time = entry[0], entry[1] # Loop through each product-value pair in the entry for product_value in entry[2:]: product, value = product_value flattened_entries.append({ 'date_time': f"{date} {time}", 'product': product, 'quantity': value }) # Turn into a pandas DataFrame df = pd.DataFrame(flattened_entries)
Step 3: Generate the Stacked Bar Chart
Now use Plotly Express to build the stacked chart. We'll map the combined date-time to the X-axis, quantities to the Y-axis, color bars by product, and enable stacking with barmode='stack':
fig = px.bar( df, x='date_time', y='quantity', color='product', barmode='stack', title='Stacked Product Quantities by Date & Time', labels={'quantity': 'Total Quantity', 'date_time': 'Date & Time'} ) # Display the chart fig.show()
Quick Breakdown:
- The flattening step ensures every product's quantity is linked to its correct date-time, which is critical for accurate stacking.
barmode='stack'tells Plotly to layer bars of different products on top of each other for each X-axis entry.- Custom labels and a title make the chart intuitive to read at a glance.
When you run this code, you'll get an interactive stacked bar chart where each X-axis tick is a date-time combination, and each bar is split into colored segments representing each product's contribution to the total quantity.
内容的提问来源于stack exchange,提问作者user7350953

