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

Plotly自定义气泡图实现及数据可视化问题求助

Plotly自定义气泡图实现及数据可视化问题求助

Hi there! Let's work through your Plotly bubble chart problems one by one, and fix up your code along the way.

第一个问题:修复DataFrame与Plotly的结合显示问题

First, let's spot a small import error in your code: you imported plotly.graph_objects twice, but px is actually the standard alias for Plotly Express, not Graph Objects. Fix that first, and we'll adjust the rest to make sure your data and chart render properly in Streamlit:

  • Replace import plotly.graph_objects as px with import plotly.express as px
  • In Streamlit, you don't need fig.show() — st.plotly_chart(fig) is enough to display the chart in your app
  • Your st.dataframe(df) already correctly shows your raw DataFrame, so that part is good to keep!

第二个问题:实现带负值区分的自定义气泡图

To create a bubble chart that highlights negative values (like the example you referenced), we can use two practical approaches — pick whichever fits your needs:

方案1:基于正负值自定义分组颜色

给数据新增一列标记值的正负,再映射到指定颜色,适合需要明确区分正负类别的场景:

import plotly.express as px 
import streamlit as st
import pandas as pd

# 原始数据
data = {
    'x': [1.5, 1.6, -1.2],
    'y': [21, 16, 46],
    'circle-size': [10, 5, 6],
}
df = pd.DataFrame(data)

# 新增列标记正负值
df['value_category'] = df['x'].apply(lambda x: '正值' if x > 0 else '负值')

# 在Streamlit展示原始数据
st.dataframe(df)

# 生成自定义颜色的气泡图
fig = px.scatter(
    df, 
    x="x", 
    y="y", 
    color="value_category",
    color_discrete_map={"正值": "blue", "负值": "red"},  # 自定义正负值对应颜色
    size='circle-size',
    title="正负值区分气泡图"
)

# 在Streamlit渲染图表
st.plotly_chart(fig)

方案2:使用渐变配色关联数值大小

直接基于x值的正负和大小使用渐变配色,适合需要体现数值连续变化的场景:

import plotly.express as px 
import streamlit as st
import pandas as pd

# 原始数据
data = {
    'x': [1.5, 1.6, -1.2],
    'y': [21, 16, 46],
    'circle-size': [10, 5, 6],
}
df = pd.DataFrame(data)

# 在Streamlit展示原始数据
st.dataframe(df)

# 生成渐变配色的气泡图
fig = px.scatter(
    df, 
    x="x", 
    y="y", 
    color="x",  # 颜色直接关联x值大小
    color_continuous_scale=px.colors.diverging.RdBu,  # 红-蓝渐变(负值红,正值蓝)
    size='circle-size',
    title="数值关联渐变气泡图"
)

# 在Streamlit渲染图表
st.plotly_chart(fig)

小提示

  • 方案1里的color_discrete_map可以换成任何你想要的颜色代码或名称
  • 方案2的渐变配色可以用Plotly内置的其他发散色板,比如BrBG,也可以自定义色值列表

如果需要调整细节来完全匹配你的预期效果,随时说哦!

备注:内容来源于stack exchange,提问作者user29295031

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 08:54:32