Python数据可视化:构建产品-类别-价值层级占比图表
Nice use case! To visualize that hierarchical breakdown—showing the overall total, product-level totals, and each category's value under the products—interactive charts like Plotly's sunburst or treemap are ideal. They let you drill down into the hierarchy and clearly see the relative sizes of each segment. Here's a complete solution:
Step 1: Install Required Libraries
If you don't have Plotly installed yet, run this command first:
pip install plotly pandas
Step 2: Full Code Implementation
import pandas as pd import plotly.express as px # Your original dataset df = pd.DataFrame({ 'Product': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'], 'Category': ['Text', 'Text2', 'Text3', 'Text4', 'Text', 'Text2', 'Text3', 'Text4'], 'Value': [80, 10, 5, 5, 5, 3, 2, 0] }) # Calculate key totals total_value = df['Value'].sum() product_totals = df.groupby('Product')['Value'].sum().reset_index() # Build hierarchical data structure hierarchical_data = [] # Add top-level "Total" node hierarchical_data.append({ 'Level1': 'Total', 'Level2': '', 'Level3': '', 'Value': total_value }) # Add product-level nodes (children of Total) for _, product_row in product_totals.iterrows(): hierarchical_data.append({ 'Level1': 'Total', 'Level2': product_row['Product'], 'Level3': '', 'Value': product_row['Value'] }) # Add category-level nodes (children of each Product) for _, category_row in df.iterrows(): # Optional: Skip zero-value categories if desired if category_row['Value'] > 0: hierarchical_data.append({ 'Level1': 'Total', 'Level2': category_row['Product'], 'Level3': category_row['Category'], 'Value': category_row['Value'] }) # Convert to DataFrame hier_df = pd.DataFrame(hierarchical_data) # Option 1: Interactive Sunburst Chart fig_sunburst = px.sunburst( hier_df, path=['Level1', 'Level2', 'Level3'], values='Value', title='Hierarchical Product-Category Value Breakdown', color='Level2', hover_data={'Value': ':,.0f'} # Format values for readability ) fig_sunburst.update_layout(margin=dict(t=50, l=0, r=0, b=0)) fig_sunburst.show() # Option 2: Interactive Treemap Chart fig_treemap = px.treemap( hier_df, path=['Level1', 'Level2', 'Level3'], values='Value', title='Product-Category Value Treemap', color='Level2', hover_data={'Value': ':,.0f'} ) fig_treemap.update_layout(margin=dict(t=50, l=0, r=0, b=0)) fig_treemap.show()
What This Does:
- The sunburst chart displays the total at the center, branching out to Products A and B (with their summed values), then each category under the respective products. You can click on segments to zoom in/out.
- The treemap uses nested rectangles sized by value, making it easy to compare the relative importance of each product and category at a glance.
- Optional: I added a check to skip zero-value categories (like B's Text4) if you don't want tiny, empty segments cluttering the chart.
内容的提问来源于stack exchange,提问作者Kelli-Jean
相关产品推荐
相关产品推荐

