I have a dataframe with a column for weeks and data captured for each week. it looks like this
JavaScript
x
16
16
1
# Import pandas library
2
import pandas as pd
3
4
# initialize list of lists
5
data = [['20', 10],
6
['21', 15],
7
['23', 14],
8
['40', 50],
9
['41', 56]]
10
11
# Create the pandas DataFrame
12
df = pd.DataFrame(data, columns=['weeks', 'counts'])
13
14
# print dataframe.
15
df
16
Now I am plotting a line chart with this data . Notice that from week 23 to week 40, we didnt have data. so my intention is to skip this weeks on the plot and only have a line chart of those weeks with available data.
Plotly orders everything automatically and it includes the missing weeks and this might cause problems when its being interpreted.
see what plotly does
JavaScript
1
7
1
import plotly.express as px
2
3
#df = px.data.gapminder().query("country=='Canada'")
4
fig = px.line(df, x="weeks", y="counts", title='Recruitment per Week')
5
#fig.write_image("images/Recruit.jpeg")
6
fig.show()
7
How can I have a break on the chart from week 23 to 40. Like the line chart to break in show that we didnt have data in those specific weeks.
Advertisement
Answer
First, I would re-index the data so weeks with no data are accounted for.
JavaScript
1
37
37
1
df['weeks'] = df['weeks'].astype(int)
2
df = df.set_index('weeks').reindex(np.arange(df['weeks'].min(),df['weeks'].max()+1)).reset_index()
3
4
>>> df
5
weeks counts
6
0 20 10.0
7
1 21 15.0
8
2 22 NaN
9
3 23 14.0
10
4 24 NaN
11
5 25 NaN
12
6 26 NaN
13
7 27 NaN
14
8 28 NaN
15
9 29 NaN
16
10 30 NaN
17
11 31 NaN
18
12 32 NaN
19
13 33 NaN
20
14 34 NaN
21
15 35 NaN
22
16 36 NaN
23
17 37 NaN
24
18 38 NaN
25
19 39 NaN
26
20 40 50.0
27
21 41 56.0
28
29
30
fig = px.line(df,
31
x='weeks',
32
y='counts',
33
title='Recruitment per Week',
34
markers=True)
35
36
fig.show()
37