【问题标题】:manipulating top and bottom margins in pyplot horizontal stacked bar chart (barh)在 pyplot 水平堆积条形图中操作顶部和底部边距(barh)
【发布时间】:2015-06-16 03:09:00
【问题描述】:

我正在尝试绘制一个水平堆叠条形图,但顶部和底部的边距大得令人讨厌。我想摆脱它或控制大小。

这是一个示例代码和图:

from random import random
Y = ['A', 'B', 'C', 'D', 'E','F','G','H','I','J', 'K']
y_pos = np.arange(len(Y))
data = [(r, 1-r) for r in [random() for i in range(len(Y))]]
print data
a,b = zip(*data)

fig = plt.figure(figsize=(8,16))
ax = fig.add_subplot(111)
ax.barh(y_pos, a,color='b',align='center')
ax.barh(y_pos, b,left=a,color='r',align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(Y, size=16)
ax.set_xlabel('X label', size=20)

plt.xlim(0,1) #removing the extra x on the right side

如果你想重新创建确切的数字,创建附图的序列采样('数据'):

[(0.2180251581652276,0.7819748418347724),(0.20639063565084814,0.7936093643491519),(0.5402540115461549,0.45974598845384507),(0.39283183355790896,0.607168166442091),(0.5082547993681953,0.4917452006318047),(0.02489004061858613,0.9751099593814139),(0.25902114354397665,0.7409788564560233),(0.12032683729286475,0.8796731627071352 ), (0.41578415717252204, 0.584215842827478), (0.5860546624151288, 0.4139453375848712), (0.20982523758445237, 0.7901747624155476])

我希望在“K”顶部以及 x 轴和“A”之间有一个更小的间隙。 如果我将 16 更改为:

fig = plt.figure(figsize=(8,16))

到 10 时,一切都缩小了,但边距仍然相对较大。

有什么想法吗? 谢谢!

【问题讨论】:

  • 关于样式,我导入 seaborn 和 font = 'family':'fantasy','weight':'normal'} matplotlib.rc('font', **font)

标签: python matplotlib margins


【解决方案1】:

您可能希望将此行添加到脚本的末尾:

plt.ylim(min(y_pos)-1, max(y_pos)+1)

这会将边距减少到半条宽度。

【讨论】:

  • 谢谢!像魅力一样工作。发帖前我在和 ylim 一起玩,但没弄好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-12
  • 1970-01-01
  • 2020-09-14
  • 2020-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多