Plotly双X轴标签旋转及轴分隔线移除问题咨询
解决方案
问题1:双X轴标签旋转无效
核心原因是未明确为每个图表元素绑定对应X轴,导致日期轴的配置无法生效。解决步骤:
- 为折线图(Scatter)和柱状图(Bar)分别指定对应的X轴(
xaxis="x2"和xaxis="x1") - 在
update_layout中同时为xaxis1和xaxis2设置rotation参数
问题2:移除X轴分隔线
通过让两个X轴重叠显示,并隐藏轴线即可实现:
- 为
xaxis2添加overlaying="x"使其覆盖在xaxis1上方 - 为两个轴设置
showline=False隐藏轴线
修改后的完整代码
import plotly.express as px import pandas as pd import numpy as np import plotly.graph_objects as go from plotly.subplots import make_subplots import itertools as it from sklearn.preprocessing import LabelEncoder from sklearn.utils import column_or_1d class MyLabelEncoder(LabelEncoder): def fit(self, y): y = column_or_1d(y, warn=True) self.classes_ = pd.Series(y).unique() return self df = pd.DataFrame([1, None, None, 4, 6, None, 2, 1], columns=["y"]) df["x"] = [1, 2, 3, 4, 5, 6, 7, 8] df["rank"] = [ "baseline", "beginner", "beginner", "apprentice", "apprentice", "expert", "expert", "expert", ] df["x_dates"] = [ "2022-01-01", "2022-01-04", "2022-01-07", "2022-01-10", "2022-01-13", "2022-01-16", "2022-01-19", "2022-01-22", ] le = MyLabelEncoder() le.fit(df["rank"]) rank = le.transform(df["rank"]) + 1 fig = make_subplots(specs=[[{"secondary_y": True}]]) # 生成颜色和线型配置 df.loc[df["y"].isna(), "line_color"] = "red" df.loc[df["y"].isna(), "line_type"] = "dash" df.loc[df["y"].notna(), "line_color"] = "black" df.loc[df["y"].notna(), "line_type"] = "solid" df["y"] = df["y"].interpolate(method="pad") # 生成坐标对 x_pairs = it.pairwise(df["x"]) x_date_pairs = it.pairwise(df["x_dates"]) y_pairs = it.pairwise(df["y"]) for x_data, x_date, y_vals, line_color, line_type in zip( x_pairs, x_date_pairs, y_pairs, df["line_color"].values, df["line_type"].values ): # 折线图绑定到xaxis2(日期轴) fig.add_trace( go.Scatter( x=x_date, y=y_vals, mode="lines", line=dict(color=line_color, dash=line_type), showlegend=False, xaxis="x2" ), secondary_y=True, ) # 柱状图绑定到xaxis1(重复次数轴) fig.add_trace( go.Bar( x=df["x"], y=rank, showlegend=False, text=rank, xaxis="x1" ), secondary_y=False, ) fig.update_layout( { "xaxis1": { "title_text": "Repetition", "tickvals": np.arange(1, np.max(df["x"]) + 1, 1), "rotation": 45, # 旋转重复次数标签 "showline": False # 隐藏轴线 }, "xaxis2": { "title_text": "Date", "tickvals": df["x_dates"], "rotation": 45, # 旋转日期标签 "overlaying": "x", # 覆盖在xaxis1上 "anchor": "y", "showline": False # 隐藏轴线 }, "yaxis": { "title_text": "placeholder", "showgrid": False, "anchor": "x", "domain": [0.0, 1.0], "side": "right", }, "yaxis2": { "title_text": "data", "anchor": "x", "overlaying": "y", "side": "left", }, } ) fig.show()
关键修改点说明
- 绑定X轴:为
Scatter和Bar元素分别添加xaxis="x2"和xaxis="x1",确保轴配置能精准作用到对应标签 - 旋转标签:在
xaxis1和xaxis2中都设置rotation=45(可根据实际需求调整角度) - 移除分隔线:通过
overlaying="x"让两个轴重叠,再用showline=False隐藏轴线,彻底消除分隔线
内容的提问来源于stack exchange,提问作者carluqcor98
相关产品推荐
相关产品推荐

