在 boxplot matplotlib 中减少 space

Reduce space inside the boxplot matplotlib

我想删除绘图边界内多余的 space

plt.boxplot(parkingData_agg['occupancy'], 0, 'rs', 0, 0.75)
plt.tight_layout() # This didn't work. Maybe it's not for the purpose I am thinking it is used for.
plt.yticks([0],['Average Occupancy per slot'])
fig = plt.figure(figsize=(5, 1), dpi=5) #Tried to change the figsize but it didn't work
plt.show()

想要的图如下图左起第二个图

使用subplots_adjust

fig = plt.figure(figsize=(5, 2))
axes = fig.add_subplot(1,1,1)
axes.boxplot(parkingData_agg['occupancy'], 0, 'rs', 0, 0.75)
plt.subplots_adjust(left=0.1, right=0.9, top=0.6, bottom=0.4)

#plt.boxplot(parkingData_agg['occupancy'], 0, 'rs', 0, 0.75)
#plt.tight_layout()
plt.yticks([0],['Average Occupancy per slot'])
plt.show()

代码中的命令顺序有点乱。

  • 您需要定义一个图形,绘图命令之前(否则会生成第二个图形)。
  • 您还需要在设置刻度标签后调用tight_layout ,这样长的刻度标签就可以被计算在内。
  • 要使位置 0 的刻度与箱线图的位置匹配,需要将其设置到该位置 (pos=[0])

这些变化将导致以下情节

import matplotlib.pyplot as plt
import numpy as np
data = np.random.rayleigh(scale=7, size=100)

fig = plt.figure(figsize=(5, 2), dpi=100)

plt.boxplot(data, False, sym='rs', vert=False, whis=0.75, positions=[0])

plt.yticks([0],['Average Occupancy per slot'])

plt.tight_layout() 
plt.show()

然后您可以更改箱线图的 widths 以匹配所需的结果,例如

plt.boxplot(..., widths=[0.75])

你当然可以把你的图放在一个子图中,而不是让坐标轴填满整个图 space,例如

import matplotlib.pyplot as plt
import numpy as np
data = np.random.rayleigh(scale=7, size=100)

fig = plt.figure(figsize=(5, 3), dpi=100)
ax = plt.subplot(3,1,2)

ax.boxplot(data, False, sym='rs', vert=False, whis=0.75, positions=[0], widths=[0.5])

plt.yticks([0],['Average Occupancy per slot'])

plt.tight_layout()
plt.show()