Plotly折线图技术咨询:网格线异常粗细与零线颜色修改
Plotly折线图技术问题解答
问题1:2024年1月日期对应的垂直网格线明显偏粗
原因
Plotly的日期型X轴会自动区分主要刻度和次要刻度:2024年1月作为月份起始节点,属于系统识别的主要刻度,默认情况下主要刻度对应的网格线会比次要刻度的网格线更粗,以此强化时间维度的层级感。
解决方案
通过update_xaxes统一设置所有网格线的宽度,或者单独对齐主要/次要刻度的网格线宽度:
# 统一所有网格线粗细(推荐) fig.update_xaxes(color="#000000", linecolor='#000000', gridcolor='#C6C6C6', gridwidth=1, # 设置为你需要的宽度,比如1像素 title_text=f'date') # 或者单独对齐主次刻度网格线宽度 # fig.update_xaxes(color="#000000", linecolor='#000000', gridcolor='#C6C6C6', # major_gridwidth=1, minor_gridwidth=1, # title_text=f'date')
问题2:修改Y轴零线(非X轴)的颜色为深色
解决方案
你提到的白色零线是Y轴的零参考线,可通过update_yaxes的zerolinecolor参数直接修改颜色,同时可通过zerolinewidth调整线条宽度:
fig.update_yaxes(color="#000000", linecolor='#000000', gridcolor='#C6C6C6', zerolinecolor='#2F0063', # 设置为目标深色,比如与折线同色 zerolinewidth=1.5, # 可选:调整零线宽度,匹配折线粗细 title_text=f'correlation')
完整修改后的代码示例
def plot_line(self): df = self.rolling_cor() """plot""" # plot single line fig = px.line(df, x=df.iloc[:, 0], y=df.iloc[:, 1]) fig.update_traces(line_color='#2F0063', line_width=1.5) # 修改X轴网格线粗细 fig.update_xaxes(color="#000000", linecolor='#000000', gridcolor='#C6C6C6', gridwidth=1, title_text=f'date') # 修改Y轴零线颜色及网格线 fig.update_yaxes(color="#000000", linecolor='#000000', gridcolor='#C6C6C6', zerolinecolor='#2F0063', zerolinewidth=1.5, title_text=f'correlation') fig.update_layout(showlegend=False, title=df.columns[1], title_font_size=30, title_x=0.5, font_family="Arial", paper_bgcolor="#FFE2DC", plot_bgcolor="#FFE2DC") # annotate last quote - first fig.add_scatter(x=[fig.data[0].x[0]], y=[fig.data[0].y[0]], mode='markers + text', marker={'color': 'blue', 'size': 14}, showlegend=False, text=[fig.data[0].y[0]], textposition='middle left') # annotate last quote - last fig.add_scatter(x=[fig.data[0].x[-1]], y=[fig.data[0].y[-1]], mode='markers + text', marker={'color': 'red', 'size': 14}, showlegend=False, text=[fig.data[0].y[-1]], textposition='middle right') # add annotation anno_p1 = "As of " anno_p2 = str(df.iloc[len(df) - 1, 0])[:10] anno_p3 = ", " anno_p4 = "the quote is at " anno_p5 = str(round(df.iloc[len(df) - 1, 1], 2)) anno_text = "".join([anno_p1, anno_p2, anno_p3, anno_p4, anno_p5]) fig.add_annotation( dict(font=dict(color='#2F0063', size=25), x=0, y=-0.09, showarrow=False, text=anno_text, textangle=0, xanchor='left', xref="paper", yref="paper")) fig.show()
内容的提问来源于stack exchange,提问作者turtle rough
相关产品推荐
相关产品推荐

