如何通过参数将Plotly图表的X轴刻度数量调整为12?
如何将Plotly图表的X轴刻度数量调整为12?
我希望将Plotly图表的X轴刻度数量调整为12,推测存在对应的配置参数,现寻求该参数的相关信息。以下为当前使用的代码及图表输出:
import re import pandas as pd import datetime import plotly.graph_objects as go def save_fig(fig,pngname): fig.write_image(pngname,format="png", width=800, height=400, scale=1) print("[[%s]]"%pngname) return def plot_stems(df): fig = go.Figure() traces = [] xname = df.columns[0] color = 'blue' lw=1 for i,yname in enumerate(df.columns): if i == 0: continue trace1 = go.Scatter( x=df[xname], y=df[yname], mode = 'markers',#'lines', 'markers', 'text' marker=dict(color=color,size=1.5*lw), error_y=dict( type='data', array=[0]*len(df[yname]), arrayminus=df[yname], color=color, thickness=1, width=0, ), ) traces.append(trace1) fig.add_traces(traces) fig.update_layout( margin=dict(l=10,t=40,r=10,b=40), plot_bgcolor='#ffffff',#'rgb(12,163,135)', paper_bgcolor='#ffffff', title="title", xaxis_title="x", yaxis_title="y", title_x=0.5, barmode='group', bargap=0.05, bargroupgap=0.0, legend=dict(x=.02,y=1), xaxis=dict( tickangle=-25, tickformat = '%m-%d %H:%M:%S',#datetime format showline=True, linecolor='black', color='black', linewidth=.5, ticks='outside', ), yaxis=dict( showline=True, linecolor='black', color='black', linewidth=.5, showgrid=True, gridcolor='grey',#'#ececec', gridwidth=.5, griddash='solid',#'dot', zeroline=True, zerolinecolor='grey', zerolinewidth=.5, showticklabels=True, ), ) fig.show() return def main(): data = [ ["2023-04-01 12:00:00.123",1], ["2023-04-01 12:00:10.123",2], ["2023-04-01 12:00:20.123",1], ["2023-04-01 12:00:30.123",5], ["2023-04-01 12:00:40.123",10], ["2023-04-01 12:00:50.123",8], ["2023-04-01 12:01:00.123",6], ["2023-04-01 12:01:10.123",9], ["2023-04-01 12:01:20.123",10], ["2023-04-01 12:01:30.123",2], ["2023-04-01 12:01:40.123",5], ["2023-04-01 12:01:50.123",9], ["2023-04-01 12:02:30.123",2], ["2023-04-01 12:02:40.123",5], ["2023-04-01 12:02:50.123",9], ] df = pd.DataFrame(data,columns=['ts','value']) df['ts'] = pd.to_datetime(df['ts'],format="%Y-%m-%d %H:%M:%S.%f") plot_stems(df) return main()
图表输出

解决方案
要指定X轴的刻度数量,直接在xaxis的配置字典中添加nticks参数并设置为12即可。Plotly会根据数据范围自动计算并生成近似指定数量的刻度(实际显示数量可能因数据区间的合理性略有调整)。
修改后的xaxis配置如下:
xaxis=dict( tickangle=-25, tickformat = '%m-%d %H:%M:%S',#datetime format showline=True, linecolor='black', color='black', linewidth=.5, ticks='outside', nticks=12 # 添加这一行,指定刻度数量 ),
如果需要更精确地控制日期轴的刻度间隔,也可以使用dtick参数(比如设置为固定的时间间隔,如dtick=60000代表1分钟,单位为毫秒),但nticks更适合直接指定刻度总数的场景。
内容的提问来源于stack exchange,提问作者lucky1928
相关产品推荐
相关产品推荐

