缩小两个方块图之间的距离

2024-06-28 19:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python和matplotlib绘制下面所示的bloxplot。有没有办法缩小X轴上两个方框图之间的距离?

enter image description here

这是我用来得到上图的代码:

import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['ytick.direction'] = 'out'
rcParams['xtick.direction'] = 'out'

fig = plt.figure()
xlabels = ["CG", "EG"]
ax = fig.add_subplot(111)
ax.boxplot([values_cg, values_eg])
ax.set_xticks(np.arange(len(xlabels))+1)
ax.set_xticklabels(xlabels, rotation=45, ha='right')
fig.subplots_adjust(bottom=0.3)
ylabels = yticks = np.linspace(0, 20, 5)
ax.set_yticks(yticks)
ax.set_yticklabels(ylabels)

ax.tick_params(axis='x', pad=10)
ax.tick_params(axis='y', pad=10)

plt.savefig(os.path.join(output_dir, "output.pdf"))

这是一个更接近我想要的视觉效果的例子(尽管我不介意方块图是否更接近彼此):

enter image description here


Tags: importmatplotlibnpfigpltaxoutvalues
0条回答
网友
1楼 · 发布于 2024-06-28 19:28:27

您可以更改绘图的纵横比,也可以使用widthskwarg(doc)这样:

ax.boxplot([values_cg, values_eg], widths=1)

使盒子更宽。

网友
2楼 · 发布于 2024-06-28 19:28:27

当代码编写时:

ax.set_xticks(np.arange(len(xlabels))+1)

您将第一个方框图放在0上,第二个方框图放在1上(尽管您随后更改了记号标签),就像在第二个“想要的”示例中一样,您将它们设置为1、2、3。 所以我认为另一种解决方案是利用xticks的位置和情节的xlim

例如使用

ax.set_xlim(-1.5,2.5)

会让他们更靠近。

网友
3楼 · 发布于 2024-06-28 19:28:27

尝试使用更改纵横比

ax.set_aspect(1.5) # or some other float

数字越大,绘图越窄(越高):

a circle will be stretched such that the height is num times the width. aspect=1 is the same as aspect=’equal’.

http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_aspect

相关问题 更多 >