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

Matplotlib绘图问题:设置X轴为百分比及实现双图叠加

我来帮你搞定这两个问题,直接上修改后的代码和详细说明:

1. 将X轴设置为百分比格式

要把X轴改成百分比显示,我们可以用matplotlib.ticker.PercentFormatter,它能自动把刻度值转换成百分比格式。根据你的X轴范围(1-8),我们可以把最大值设为8,这样每个X值会被计算为(x/8)*100%,刚好对应从12.5%到100%的拥堵比例。

2. 实现上下布局的连贯“叠加”显示

你说的“叠加显示”应该是指让两个上下布局的图表共享X轴,这样X轴对齐且只显示一次,视觉上更紧凑连贯。我们可以在创建第二个子图时加上sharex=ax参数,让它共享第一个子图的X轴。


修改后的完整代码

#!/usr/bin/env python3
import numpy as np
import math
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker  # 导入ticker模块处理百分比

fig = plt.figure(figsize=(8, 6))  # 可根据需求调整图表大小

# 上方指数函数曲线(Latency vs Congestion)
x = np.arange(1,9,1)
y = [math.exp(_) for _ in x]
ax = fig.add_subplot(211)
ax.plot(x, y)
ax.set_ylabel('Latency')  # 替换为你需要的Y轴标签
# 隐藏上方子图的X轴标签,避免重复显示
ax.set_xlabel('')
# 设置X轴为百分比格式
ax.xaxis.set_major_formatter(ticker.PercentFormatter(xmax=8))  # xmax对应X轴最大值

# 保留你原有的图表美化设置
ax.set_yticks([],[])
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.yaxis.set_tick_params(which='major', direction='out')
ax.set_ymargin(1)

# 下方效用函数曲线(Throughput vs Congestion),共享上方的X轴
ax1 = fig.add_subplot(212, sharex=ax)  # 添加sharex=ax参数实现X轴共享
mu = 5
variance = 1
sigma = math.sqrt(variance)
x_normal = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
y_normal = mlab.normpdf(x_normal, mu, sigma)
x_normal = [0, 0] + list(x_normal)
y_normal = [0, 0] + list(y_normal)
ax1.plot(x_normal, y_normal)
ax1.set_ylabel('Throughput')  # 替换为你需要的Y轴标签
ax1.set_xlabel('Congestion')  # 仅在下方子图显示X轴标签

# 保留你原有的图表美化设置
ax1.set_yticks([],[])
ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')
ax1.set_ymargin(1)

fig.tight_layout()
fig.savefig('bw-latency.pdf', format='pdf', bbox_inches='tight', pad_inches=0.1, dpi=1000)
plt.clf()
plt.close()

关键修改点说明:

  • 百分比X轴:通过ticker.PercentFormatter(xmax=8),把X轴的每个数值转换成相对于最大值8的百分比,比如x=1对应12.5%,x=8对应100%。如果你的拥堵比例是从0到100%,可以直接把x定义为np.arange(0, 101, 12.5),然后把xmax设为100,这样刻度会直接显示0%、12.5%...100%。
  • 共享X轴:第二个子图用sharex=ax,这样两个图的X轴完全对齐,而且上方子图的X轴刻度会被隐藏,只在下方显示,避免重复,实现你想要的“叠加”连贯效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:16:51