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

如何将Seaborn绘制的州与年度贷款总额嵌套柱状图转为Plotly?

Convert Seaborn Nested Bar Plot to Plotly

Got it, let's walk through converting your Seaborn nested bar chart to Plotly— it's straightforward with Plotly Express, which mirrors a lot of Seaborn's intuitive syntax while adding interactive features. Here's the step-by-step implementation:

Step 1: Import Plotly Express

First, make sure you have Plotly installed, then import the library:

import plotly.express as px

Step 2: Replicate the Bar Chart

This code will match your Seaborn setup, including grouping, color palette, and style:

# Create the grouped (nested) bar plot
fig = px.bar(
    total_amount_group_year,
    x="State",
    y="Loan_Amount_000",
    color="As_of_Year",  # Matches Seaborn's `hue` parameter
    barmode="group",     # Enables nested/grouped bars (critical for this chart type)
    title="Total Loan Amount aggregated by State and Year",
    color_discrete_sequence=px.colors.qualitative.Flatui,  # Matches Seaborn's flatui palette
    template="bmh"       # Replicates the 'bmh' style from your original code
)

Step 3: Adjust Axes & Styling

Now let's mirror the Seaborn customizations like axis labels, font sizes, and removing the left spine:

# Set axis labels with custom font sizes
fig.update_xaxes(title_text="State", title_font=dict(size=15))
fig.update_yaxes(title_text="Total Loan Amount", title_font=dict(size=15))

# Remove the left axis line (equivalent to `g.despine(left=True)` in Seaborn)
fig.update_yaxes(showline=False, linewidth=0)

# Optional: Format y-axis ticks (match your original `set_yticklabels` logic)
# Example: Format numbers with commas, adjust based on your needs
fig.update_yaxes(tickformat=",")

Step 4: Show the Interactive Chart

Finally, render the interactive Plotly chart:

fig.show()

Key Equivalences to Your Seaborn Code

  • color="As_of_Year" = Seaborn's hue="As_of_Year"
  • barmode="group" = Creates the nested bar layout (same as Seaborn's factorplot bar type)
  • color_discrete_sequence = Matches your palette=sns.color_palette(flatui)
  • template="bmh" = Replaces plt.style.use('bmh')
  • update_xaxes/update_yaxes = Replaces g.set_xlabels/g.set_ylabels

If you need more control (like adjusting bar width, adding hover tooltips with extra data, or customizing the legend), you can extend this code with Plotly's graph objects API, but Plotly Express is perfect for a direct conversion here.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:14:03