How to customize axis ticks label on X or Y axis in Pandas?

Viewed 468

I am facing difficulties trying to customize the x-axis ticks labels. I am plotting a graph on Count of Laptops sold daily. What I want is the x-axis to show all the 7-days Day and corresponding count value including days where 0 laptops are sold. I would also like the x-axis(day) to be sorted in ascending order. How do I do that? Below is my code:

count = [5,1,12,3,4]
day = pd.Series(['3','2','4','5','7'], dtype="category")
df = pd.DataFrame({'day':day, 'count':count})

trace1 = go.Bar(x=df['day'], y=df['count'], name= 'Day', text=df['count'], textposition='auto', marker_color='rgb(55, 83, 109)')

data = [trace1]

layout = go.Layout(title='Laptops sold daily', xaxis=dict(title='Day'), yaxis=dict(title='Count of Laptops'), hovermode='closest')
fig = go.Figure(data=data, layout=layout)
pyo.iplot(fig)

Dataframe Output

Graph Output

Output Graph based on Accepted Solution: enter image description here

3 Answers

Merge your dataframe first on a series of all days you potentially need. Days without sales will have a count of NaN which causes the sales count column become float. We finally replace the NaNs with 0 and convert back to int.

df = df.merge(pd.Series(range(1,8), name='day').astype(str), how='right').fillna(0).astype(int)

The resulting dataframe will be automatically sorted as the right join preserves to order of the (right) keys, which you provide in ascending order.

Since you're using pyo.iplot(fig), I would like to show you how you can do it more easily using plotly as a plotting backend for pandas. The data munging is identical to the suggestion from Stef.

Code

# imports and settings
import pandas as pd
pd.options.plotting.backend = "plotly"

# data
count = [5,1,12,3,4]
day = pd.Series(['3','2','4','5','7'], dtype="category")
df = pd.DataFrame({'day':day, 'count':count})
df = df.merge(pd.Series(range(1,8), name='day').astype(str), how='right').fillna(0).astype(int)

# plotly
fig = df.plot(kind='bar', x = 'day', y = 'count', text='count')
fig.update_traces(marker_color='rgb(55, 83, 109)')

Plot

enter image description here

Another approach is to update the x-axis with a dictionary of days of the week and day number, so that the x-axis can be extended to the name of the day.

df.set_index('day', inplace=True)
weekdaynum = {'1':'Mon','2':'Tue','3':'Wed','4':'Thu','5':'Fri','6':'Sat','7':'Sun'}
df = df.reindex(weekdaynum.keys(), fill_value=0)
df.reset_index(inplace=True)
df.day = df.day.map(weekdaynum)

    day     count
0   Mon     0
1   Tue     1
2   Wed     5
3   Thu     12
4   Fri     3
5   Sat     0
6   Sun     4

enter image description here

Related