python - 像plotly.express 中一样使用plotly.graph_objs 创建直方图

标签 python plotly data-visualization histogram

我正在做可视化,我可以在plotly express中创建我想要的内容,但我必须使用不同的功能多次执行此操作,因此我更喜欢使用graph_objs来制作子图,但我不知道如何创建它们。

fig = px.histogram(eda, x="HeartDisease", color="Sex", barmode="group", height=450, width = 450) fig.show()

enter image description here

但是当我尝试在图表 fig.add_trace(go.Histogram( x = eda['HeartDisease'], name=eda.Sex)) 中做到这一点时

错误:“名称”属性是一个字符串,必须指定为: - 字符串 - 将转换为字符串的数字

fig.add_trace(go.Histogram( x = eda['HeartDisease'], color=eda.Sex))

错误:错误的属性路径:颜色

希望你能帮助我!

数据

<表类=“s-表”> <标题> 性别 心脏病 <正文> 男性 心脏病 女性 正常 女性 心脏病 男性 心脏病 男性 正常

最佳答案

由于没有数据呈现,我根据 official reference 中的示例使用 graph_objects 创建了直方图。 。我们将通过提取分类变量来处理它,而不是像在express中那样指定分类变量。

import plotly.graph_objects as go

df = px.data.tips()

fig = go.Figure()
fig.add_trace(go.Histogram(histfunc="count",
                           y=df.query('sex == "Female"')['total_bill'],
                           x=df.query('sex == "Female"')['day'],
                           name="Female")
             )
fig.add_trace(go.Histogram(histfunc="count",
                           y=df.query('sex == "Male"')['total_bill'],
                           x=df.query('sex == "Male"')['day'],
                           name="Male")
             )

fig.update_layout(xaxis_title='day', yaxis_title='Count', legend_title='sex')
fig.update_xaxes(categoryorder='array', categoryarray=["Thur", "Fri", "Sat", "Sun"])

fig.show()

enter image description here

ploty.express版本

import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="day", color='sex', barmode='group', category_orders=dict(day=["Thur", "Fri", "Sat", "Sun"]))
fig.show()

enter image description here

关于python - 像plotly.express 中一样使用plotly.graph_objs 创建直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71623896/

相关文章:

Python 点击​​ : custom error message

python - 在 jupyter notebooks : Validation fails when saving 中作图

python - 使用 Pandas GroupBy 和 size()/count() 生成聚合的 DataFrame

python - 在 Google-Colab 中使用 Python3 创建词云时应该如何使用 Arial 字体?

python - 单击破折号中的按钮后从数据框中填充破折号表

data-visualization - 当你有很多变量时,如何从 Rstudio 中提取可见的散点图矩阵?

javascript - Highcharts:使用 Google Analytics 捕获事件操作以导出图表

php - 在 PHP 中处理内存数据

Python 字典未返回所有项目

r - 使用 Shiny 的应用程序创建响应式(Reactive)数据框