python csv中的plotly条形图计数项目

时间:2019-09-16 10:02:59

标签: python csv charts plotly

我有一个具有以下结构的csv文件:

enter image description here

我写了这段代码:

import pandas as pd
import plotly.express as px

input_file = "inf.csv"
df = pd.read_csv(input_file)
fig = px.bar(df,
             x='Date',
             y='User',
             title='Test',
             color='Items',
             barmode='stack')

fig.show()

,这是输出: enter image description here

我想在Y轴上放置的不是用户,而是一个数字,该数字用于计算同一天存在多少用户。 我该怎么办?

1 个答案:

答案 0 :(得分:0)

您可以使用df.groupby('Date').count().reset_index()获得所需的数据结构。

情节:

enter image description here

代码:

import pandas as pd
from plotly.subplots import make_subplots
import plotly.express as px
import plotly.graph_objs as go
import plotly.io as pio

#pio.renderers.default = 'jupyterlab'

# Sample data
d={'Date': ['01/08/2019', '01/08/2019', '07/08/2019', '12/08/2019',
            '26/08/2019', '29/08/2019', '29/08/2019'],
   'User':['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7'],
   'Items': ['Pen', 'Ruler', 'Rubber', 'Rubber', 'Ruler', 'Ruler', 'Pen']
  }

# data strucutre
df=pd.DataFrame(d)
dfg=df.groupby('Date').count().reset_index()
dfg=dfg.rename(columns={"User": "Users"})

# plot structure
fig = px.bar(dfg,
             x='Date',
             y='Users',
             title='Test',
             #color='Items',
             barmode='stack')

# plot
fig.show()