Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

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

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

question from:https://stackoverflow.com/questions/65933037/how-to-customize-axis-ticks-label-on-x-or-y-axis-in-pandas

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...