简体   繁体   English

如何使用 plotly 与颜色参数 plot 条形图

[英]how to plot bar chart using plotly with color parameter

 df=pd.DataFrame({'gender':['F','F','M','M','M','M','M'],
                     'country':['USA','Belgium','USA','Russia','India','Belgium','Canada'],
                     'count':[123,421,112,445,21,442,226],
                     })

   gender  country     count
0   F       USA         123
1   F     Belgium       421
2   M       USA         112
3   M     Russia        445
4   M     India         21
5   M     Belgium       442
6   M     Canada        226

I want to plot a bar char that display the above table using Plotly package.我想 plot 使用Plotly package 显示上表的条形字符。 For this i used the code below but it crash and display error:为此,我使用了下面的代码,但它崩溃并显示错误:

fig = px.histogram(df,x='gender', y='count' ,color =['gender','country'],barmode = 'group')

Error:错误:

ValueError: All arguments should have the same length. ValueError:所有 arguments 应具有相同的长度。 The length of argument color is 2, whereas the length of previously-processed arguments ['gender', 'count'] is 7参数color的长度是 2,而之前处理的 arguments ['gender', 'count'] 的长度是 7

expected output:预期 output:

在此处输入图像描述

Try either:尝试:

fig = px.histogram(df,x='gender', y='count' ,color ='gender',barmode = 'group')

or或者

fig = px.histogram(df,x='gender', y='count' ,color ='country',barmode = 'group')

It would also help if you could clarify what you are trying to accomplish.如果您能澄清您要完成的工作,这也会有所帮助。 Your data doesn't make much sense.你的数据没有多大意义。 I'm not exactly sure what you are trying to achieve.我不确定您要达到的目标。

EDIT: Your clarification didn't help much, but this may be what you're looking for:编辑:您的澄清没有太大帮助,但这可能是您正在寻找的:

fig = px.histogram(df, x='country', y='count', color = 'gender')

or based on your picture或根据您的图片

fig = px.histogram(df, x="gender", y="count",color='country', barmode='group')

according to the documents color parameter takes: Either a name of a column in data_frame, or a pandas Series or array_like object for that i create a Series and assigned to color根据文档颜色参数采用: data_frame 中的列名称,或者 pandas 系列或 array_like object为此我创建一个系列并分配给color

the code becomes as below:代码如下:

cat = df[['gender','country']].agg(', '.join, axis=1)
fig = px.histogram(df,x=gender, y='count' ,color = cat,barmode = 'group')
                
  

      

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM