You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Plotly中按类别划分的子图设置独立的X轴与Y轴?

Solution: Independent Axes for Each Facet Subplot

To make each subplot display only category-specific products on the X-axis and scale the Y-axis to match the category's maximum QTY, you can adjust your Plotly Express code by disabling shared axes and setting custom Y-axis ranges per category. Here's the implementation:

import plotly.express as px 
import pandas as pd 

# Your original dataset
data = {'Category':["Toys","Toys","Toys","Toys","Food","Food","Food","Food","Food","Food","Food","Food","Furniture","Furniture","Furniture"], 
        'Product':["AA","BB","CC","DD","SSS","DDD","FFF","RRR","EEE","WWW","LLLLL","PPPPPP","LPO","NHY","MKO"], 
        'QTY':[100,200,300,50,20,800,300,450,150,320,400,1000,150,900,1150]} 
df = pd.DataFrame(data) 

# Precompute the maximum QTY value for each category
category_max_qty = df.groupby('Category')['QTY'].max().to_dict()

# Create the bar plot with independent axes for each facet
fig = px.bar(
    df, 
    x="Product", 
    y="QTY", 
    barmode="group",
    facet_col="Category",
    shared_xaxes=False,  # Disable shared X-axis to show only category-specific products
    shared_yaxes=False   # Disable shared Y-axis to allow custom scaling per category
)

# Adjust Y-axis range for each subplot to match its category's max QTY (with 10% padding)
categories = df['Category'].unique()
for idx, category in enumerate(categories):
    # Target the correct Y-axis (yaxis, yaxis2, yaxis3, etc.)
    yaxis_key = f'yaxis{idx+1}' if idx > 0 else 'yaxis'
    max_qty = category_max_qty[category]
    fig.layout[yaxis_key].update(range=[0, max_qty * 1.1])  # Padding ensures bars don't touch the top edge

# Optional: Rotate X-axis labels to prevent overlap with longer product names
for axis in fig.layout:
    if axis.startswith('xaxis'):
        fig.layout[axis].update(tickangle=45)

fig.show()

Key Changes Explained:

  • Disable Shared Axes: The shared_xaxes=False and shared_yaxes=False parameters force Plotly to create independent axes for each subplot. This automatically restricts each X-axis to only show products belonging to its category.
  • Precompute Category Max Values: Using groupby lets us calculate the highest QTY for each category, which we use to set the Y-axis range.
  • Custom Y-axis Scaling: Looping through each category and updating its Y-axis range ensures the scale fits exactly to the data in that subplot (the 10% padding adds visual breathing room).
  • Label Rotation: Rotating X-axis labels improves readability for longer product names like "LLLLL" or "PPPPPP".

内容的提问来源于stack exchange,提问作者Galat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 12:07:38