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

如何让Matplotlib箱线图缩放时保持固定宽度?

问题描述

我用Matplotlib绘制的箱线图X轴位置间隔很大,希望实现缩放图表时,箱线图的宽度保持固定,不受缩放级别影响——类比plot()或scatter()中的标记,缩放图表区域时它们在屏幕上的尺寸始终不变。默认绘制的箱线图缩小后会变窄、放大后会变宽,修改boxplot()的widths参数仅能改变初始宽度,但仍会随缩放级别变化。

代码片段

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(1)

# 生成随机数据
N = 10
y1 = np.random.randn(N)
y2 = np.random.randn(N)
y3 = np.random.randn(N)

data = [y1,y2,y3]

names = ["Near","Far","Farther"]

x_positions = [1,10,100]

fig,ax = plt.subplots()
ax.boxplot(data,positions =x_positions)
ax.set_xticklabels(names)
plt.xticks(rotation=45, ha='right')

plt.show()

效果展示

  • 缩小视图:箱线图宽度大幅变窄,几乎难以分辨
  • 放大视图:箱线图宽度显著变宽,占据过多X轴空间

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 06:54:55