Skip to main content
 首页 » 编程设计

python之箱线图不同边的 Matplotlib 刻度方向

2025年04月02日19findumars

在箱线图的左侧和右侧设置刻度方向的方法是什么? 当我 x_or_y_axis.set_tick_params(direction='whatever') 它改变方框两侧刻度的方向:

  _______________        _______________ 
-|               |-     |-             -| 
 |               |      |-             -| 
-|               |-     |-             -| 
 |               |      |-             -| 
-|_______________|-  or |_______________| 

但我需要:

  _______________         _______________ 
 |-              |-     -|             -| 
 |               |       |              | 
 |-              |-     -|             -| 
 |               |       |              | 
 |-______________|-  or -|_____________-| 

请您参考如下方法:

一种选择是使用 ax.twinx() 创建双轴,然后您可以分别控制两个轴上的 yticks。

您可能还想在两个轴之间共享 y 轴,以便两个轴之间的轴限制和刻度相同。我们可以使用答案 here这样做。

这是一个最小的例子,修改自 boxplot demo :

import matplotlib.pyplot as plt 
import numpy as np 
 
# fake up some data 
spread = np.random.rand(50) * 100 
center = np.ones(25) * 50 
flier_high = np.random.rand(10) * 100 + 100 
flier_low = np.random.rand(10) * -100 
data = np.concatenate((spread, center, flier_high, flier_low), 0) 
 
# Make the figure and axes 
fig,ax = plt.subplots(1) 
 
# Add you twin axes 
ax2 = ax.twinx() 
 
# Set the ticks to the outside on the right only 
ax2.tick_params(axis='y',direction='out') 
 
# Make sure the ticks and axes limits are shared between the left and right 
ax.get_shared_y_axes().join(ax,ax2) 
 
# basic boxplot 
ax.boxplot(data) 
 
plt.show()