You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:Pandas绘图时X轴显示名称不完整且重复

Pandas+Matplotlib双轴折线图X轴标签重复/显示不完整问题解决方法

问题描述

使用Pandas结合Matplotlib绘制双轴折线图时,X轴(对应数据的Brand列)出现标签重复、显示不完整的情况,相关代码如下:

导入的库

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from plotly.offline import iplot
import plotly as py
import plotly.tools as tls

%matplotlib inline

原绘图代码

ax = df.plot.line(x="Brand", y="Range", legend=False)
ax2 = ax.twinx()
df.plot.line(x="Brand", y="Seats", ax=ax2, legend=False, color="#d86e39")
plt.xticks(rotation='vertical')
ax.figure.legend()
plt.show()

问题原因

Pandas的plot.line()方法每次调用时,都会自动生成X轴的刻度与标签。当通过twinx()创建双轴后,第二次调用plot.line()会再次绘制X轴元素,导致标签重复;显示不完整则是因为未调整布局,标签被画布边缘截断。

解决方法

方法1:修改Pandas绘图逻辑,避免重复绘制X轴

让第二个绘图操作不生成X轴刻度,再统一设置X轴的唯一标签,同时调整布局解决显示截断问题:

ax = df.plot.line(x="Brand", y="Range", legend=False)
ax2 = ax.twinx()
# 第二个绘图不生成X轴刻度
df.plot.line(x="Brand", y="Seats", ax=ax2, legend=False, color="#d86e39", xticks=[])

# 统一设置X轴刻度与标签
ax.set_xticks(range(len(df['Brand'].unique())))
ax.set_xticklabels(df['Brand'].unique(), rotation='vertical')
# 添加图例并调整布局
ax.figure.legend(['Range', 'Seats'])
plt.tight_layout()
plt.show()

方法2:改用Matplotlib原生API绘制

直接使用Matplotlib的原生方法绘制双轴图,从根源避免Pandas自动重复绘制X轴:

fig, ax = plt.subplots()

# 绘制第一个Y轴数据
ax.plot(df['Brand'], df['Range'], label='Range')
ax.set_xlabel('Brand')
ax.set_ylabel('Range')
ax.tick_params(axis='x', rotation=90)

# 创建双轴并绘制第二个Y轴数据
ax2 = ax.twinx()
ax2.plot(df['Brand'], df['Seats'], color='#d86e39', label='Seats')
ax2.set_ylabel('Seats')

# 添加图例并调整布局
fig.legend(loc='upper right')
plt.tight_layout()
plt.show()

内容的提问来源于stack exchange,提问作者Dashz_Altair_AFC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 09:15:14