如何去除Plotly直方图坐标轴的小数位?
问题描述
我有一个如下所示的直方图:
我希望将坐标轴的显示从0.0-50.0改为0-50,即去除小数位。以下是我的部分代码:
fig = px.histogram(dataset, x=labels, y=hist[0],histnorm='percent') fig.update_layout(bargap=0,title='Session per day',xaxis_title="salesperday", yaxis_title="% of Clinets") fig.update_traces(marker_line_width=1,marker_line_color="white",texttemplate='%{y:.2f}') fig.show()
请问是否有实现该需求的方法?感谢解答。
解决方案
直接在update_layout中给目标坐标轴设置tickformat参数,就能把刻度显示改成整数格式,去掉小数位:
如果要修改的是Y轴(你的Y轴范围是0-50),修改代码如下:
fig = px.histogram(dataset, x=labels, y=hist[0],histnorm='percent') fig.update_layout( bargap=0, title='Session per day', xaxis_title="salesperday", yaxis_title="% of Clinets", yaxis=dict(tickformat='d') # 设置Y轴刻度为整数格式 ) fig.update_traces(marker_line_width=1,marker_line_color="white",texttemplate='%{y:.2f}') fig.show()
其中tickformat='d'是Plotly的整数格式符,会强制刻度显示为整数。
如果需要调整X轴的话,同理在update_layout里添加xaxis=dict(tickformat='d')即可。
要是你想指定刻度的间隔(比如每10个单位显示一个刻度),可以配合dtick参数:
yaxis=dict(tickformat='d', dtick=10)
这样Y轴就会显示0、10、20...50这些整齐的整数刻度了。
内容的提问来源于stack exchange,提问作者python_pi
相关产品推荐
相关产品推荐

