I'm trying to create a simple line chart with the date field on the X axis and the count of rows on the Y. I'm using the following code:
import plotly.express as px
data = {'Project': ['Project 1', 'Project 2', ' Project 3', 'Project 4', 'Project 5', 'Project 6', 'Project 7', 'Project 8', 'Project 9', 'Project 10'],
'Date': ['10/1/2020', '10/1/2020', '11/1/2020', '12/1/2020', '12/1/2020', '12/1/2020', '2/1/2021', '2/1/2021', '3/1/2021', '4/1/2021']}
df2 = pd.DataFrame(data, columns = ['Project','Date'])
fig = px.line(df2, x= "Date", y = "Project", title='<b>Project</b>')
fig.show()
But when I do that the project names are on the X axis instead of the count of projects for each date.
Does anyone know how I can add a count of rows so it shows the number of projects for each month of Date on the line chart?
You need to groupby
and count
the rows in pandas before sending to plotly. Also, your sample does not show it, but if you expect different dates within the same month and you only care for the year/month then you need to apply some rounding before grouping (or extract the year & month from the date with data['Date'].dt.year
and data['Date'].dt.month
, whichever you prefer).
Take this slightly different sample with 10/2 thrown in there
import plotly.express as px
data = {'Project': ['Project 1', 'Project 2', ' Project 3', 'Project 4', 'Project 5', 'Project 6', 'Project 7', 'Project 8', 'Project 9', 'Project 10'],
'Date': ['10/1/2020', '10/2/2020', '11/1/2020', '12/1/2020', '12/2/2020', '12/1/2020', '2/1/2021', '2/1/2021', '3/1/2021', '4/1/2021']}
df2 = pd.DataFrame(data, columns = ['Project','Date'])
df2['Date'] = pd.to_datetime(df2['Date'])
df_grouped = (
df2.groupby(
# normalize all dates to start of month
df2['Date'].astype('datetime64[M]')
)['Project'].count().rename('Count').to_frame()
)
df_grouped['Names'] = (
df2.groupby(df2['Date'].astype('datetime64[M]')
)['Project'].agg(',<br> '.join)
)
print(df_grouped)
fig = px.line(
df_grouped, y='Count', title='<b>Projects per month</b>',
hover_data=['Names']
)
fig.write_html('fig1.html', auto_open=True)
Update: as requested, this new code shows the project names on hover.
Output
Count Names
Date
2020-10-01 2 Project 1,<br> Project 2
2020-11-01 1 Project 3
2020-12-01 3 Project 4,<br> Project 5,<br> Project 6
2021-02-01 2 Project 7,<br> Project 8
2021-03-01 1 Project 9
2021-04-01 1 Project 10
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments