减小boxplot图中的间距matplotlib

3
我希望能够去掉图表边框内部的额外空间。
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()

enter image description here

期望的图形如下所示,即下图中从左数第二个图形。enter image description here

2
你是指y方向上的空间吗?试着调整plt.ylim()tight_layout()用于管理子图之间的空间。 - Thomas Kühn
1
我猜你忘了告诉我们你想要的情节是什么样子的。 - ImportanceOfBeingErnest
@ImportanceOfBeingErnest 谢谢您的回答,非常有帮助。我想要减少箱线图和图表边框之间的填充距离 :) - Abhijay Ghildyal
仍然不太清楚,基本上有这些选项。您没有描述您想要哪一个。 - ImportanceOfBeingErnest
抱歉,下次我会尽量清晰明了。我会在问题中添加这个。 - Abhijay Ghildyal
2个回答

7
代码中的命令顺序有点混乱。
  • 需要在绘图命令之前定义一个图形(否则会产生第二个图形)。
  • 还需要在设置刻度标签后调用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()

您可以更改箱线图的宽度以匹配所需的结果,例如

enter image description here

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

当然,您可以将您的图表放在子图中,以便不占据整个图形的空间,例如:

enter image description here

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()

enter image description here


1
使用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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接