[英]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.我在尝试自定义 x 轴刻度标签时遇到了困难。 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.我想要的是 x 轴显示所有 7 天的天数和相应的计数值,包括售出 0 台笔记本电脑的天数。 I would also like the x-axis(day) to be sorted in ascending order.我还希望 x 轴(天)按升序排序。 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 Dataframe Output
Output Graph based on Accepted Solution: Output 图表基于接受的解决方案:
Merge
your dataframe first on a series of all days you potentially need.在您可能需要的所有日子里,首先Merge
您的 dataframe。 Days without sales will have a count of NaN
which causes the sales count column become float.没有销售的天数将具有NaN
计数,这会导致销售计数列变为浮动。 We finally replace the NaN
s with 0
and convert back to int
.我们最终将NaN
替换为0
并转换回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.生成的 dataframe 将自动排序,因为右连接保留到(右)键的顺序,您按升序提供。
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 .由于您使用的是pyo.iplot(fig)
,我想向您展示如何使用plotly 作为 pandas 的绘图后端更轻松地做到这一点。 The data munging is identical to the suggestion from Stef.数据处理与 Stef 的建议相同。
# 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)')
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.另一种方法是使用包含星期几和日期编号的字典来更新 x 轴,以便 x 轴可以扩展到日期的名称。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.