如何使用 plotly 使用 python 绘制条形图
how to plot a bar chart using plotly using python
我有以下数据框
df=pd.DataFrame({'dept':['dept1','dept2','dept3','dept4','dept5'],
'subd':['hndf','nbf','asx','qwe','def'],
'jju':['0','1','1','NA','1'],
'rob':['1','0','NA','1','1'],
'ans':['0','0','1','NA','1'],
'zsd':['1','NA','1','1','1'],
'count':['4','3','3','2','4']}
dept subd jju rob ans zsd count
0 dept1 hndf 0 1 0 1 4
1 dept2 nbf 1 0 0 NA 3
2 dept3 asx 1 NA 1 1 3
3 dept4 qwe NA 1 NA 1 2
4 dept5 def 1 1 1 1 4
我需要使用 plotly.graph_objs 包
绘制条形图
哪里
- X轴是
df.loc[:, 'jju':'zsd']
- Y轴是'0'和'1'
的个数
预期结果 X 轴上的每个项目将有 2 个条形
现在我尝试了这个代码:
import pandas as pd
import plotly.graph_objs as go
res = []
for col in df.loc[:, 'jju':'zsd'].columns:
res.append(
go.Bar(
x= df.index.values.tolist(),
y = df[col].values.tolist(),
name = col
)
)
layout = go.Layout(barmode = 'group')
fig = go.Figure(data = res,layout = layout)
fig.show()
但这不是我想要的 return 所以我哪里做错了??
这是你需要的吗?
import plotly.express as px
fig=px.histogram(df,x=['jju','rob','ans','zsd'],barmode="group")
fig.show()
如果您需要忽略“NA”,您应该将它们替换为 np.nan
值:
df=df.replace('NA',np.nan)
fig=px.histogram(df,x=['jju','rob','ans','zsd'],barmode="group")
fig.show()
我有以下数据框
df=pd.DataFrame({'dept':['dept1','dept2','dept3','dept4','dept5'],
'subd':['hndf','nbf','asx','qwe','def'],
'jju':['0','1','1','NA','1'],
'rob':['1','0','NA','1','1'],
'ans':['0','0','1','NA','1'],
'zsd':['1','NA','1','1','1'],
'count':['4','3','3','2','4']}
dept subd jju rob ans zsd count
0 dept1 hndf 0 1 0 1 4
1 dept2 nbf 1 0 0 NA 3
2 dept3 asx 1 NA 1 1 3
3 dept4 qwe NA 1 NA 1 2
4 dept5 def 1 1 1 1 4
我需要使用 plotly.graph_objs 包
绘制条形图哪里
- X轴是
df.loc[:, 'jju':'zsd']
- Y轴是'0'和'1' 的个数
预期结果 X 轴上的每个项目将有 2 个条形
现在我尝试了这个代码:
import pandas as pd
import plotly.graph_objs as go
res = []
for col in df.loc[:, 'jju':'zsd'].columns:
res.append(
go.Bar(
x= df.index.values.tolist(),
y = df[col].values.tolist(),
name = col
)
)
layout = go.Layout(barmode = 'group')
fig = go.Figure(data = res,layout = layout)
fig.show()
但这不是我想要的 return 所以我哪里做错了??
这是你需要的吗?
import plotly.express as px
fig=px.histogram(df,x=['jju','rob','ans','zsd'],barmode="group")
fig.show()
如果您需要忽略“NA”,您应该将它们替换为 np.nan
值:
df=df.replace('NA',np.nan)
fig=px.histogram(df,x=['jju','rob','ans','zsd'],barmode="group")
fig.show()