我试图绘制一个条形图,销售与类别。以下是我的数据框架。
S2PName-Category S2BillDate totSale count
0 Beverages 2020-03-06 4452.62 252
1 Food 2020-03-06 36556.91 774
2 Others 2020-03-06 608.95 99
3 Snacks 2020-03-06 2662.75 139
4 Juice 2020-03-06 2139.49 40
5 IceCream 2020-03-06 135.00 4
6 OOB 2020-03-06 390.00 20
我的代码 :
data = [go.Bar(x=df['S2PName-Category'].unique(),
y=df[df['S2PName-Category']==category]['totSale'],
name = category) for category in df['S2PName-Category'].unique()]
layout = go.Layout(title='Category wise performance',
xaxis = dict(title = 'Categories', automargin = True),
yaxis = dict(tickprefix= '₹', tickformat=',.2f',type='log',autorange = True),
hovermode = 'closest',
plot_bgcolor = colors['background'],
paper_bgcolor = colors['background'],
font = dict(color = colors['text'])
)
只有类别('S2PName-Category')的Beverages被填充在X轴上,其他的没有被填充。谁能指出哪里出了问题,以及如何解决这个问题?谢谢!
试用2:我在尝试其他的可能性,由于列表的理解,我的条形图被分组,有什么方法可以让独特的类别被绘制?
代码 :
data = [go.Bar(x=df['S2PName-Category'],
y=df['totSale'],
name = category) for category in df['S2PName-Category'].unique()]
layout = go.Layout(title='Category wise performance',
xaxis = dict(title = 'Categories', automargin = True),
yaxis = dict(tickprefix= '₹', tickformat=',.2f',type='log',autorange = True),
hovermode = 'closest',
plot_bgcolor = colors['background'],
paper_bgcolor = colors['background'],
font = dict(color = colors['text'])
)
如果你提供的数据样本确实代表了你的真实数据源,你可以直接用以下方法设置一个图。go.Figure()
并为每一个 'S2PName-Category'
如果这样还不够,你必须提供一个更好的数据样本。
完整的代码。
import plotly.express as px
import pandas as pd
import plotly.graph_objs as go
df = pd.DataFrame({'S2PName-Category': {0: 'Beverages',
1: 'Food',
2: 'Others',
3: 'Snacks',
4: 'Juice',
5: 'IceCream',
6: 'OOB'},
'S2BillDate': {0: '2020-03-06',
1: '2020-03-06',
2: '2020-03-06',
3: '2020-03-06',
4: '2020-03-06',
5: '2020-03-06',
6: '2020-03-06'},
'totSale': {0: 4452.62,
1: 36556.91,
2: 608.95,
3: 2662.75,
4: 2139.49,
5: 135.0,
6: 390.0},
'count': {0: 252, 1: 774, 2: 99, 3: 139, 4: 40, 5: 4, 6: 20}})
fig = go.Figure()
for cat in df['S2PName-Category']:
dft = df[df['S2PName-Category']==cat]
fig.add_traces(go.Bar(x=dft['S2PName-Category'], y=dft['totSale'], name=cat))
fig.show()