如何让图中柱子的宽度无论柱子数量如何都保持一致?

2 投票
1 回答
3009 浏览
提问于 2025-04-16 02:34

我想让柱子的宽度保持一致,无论比较的柱子数量是多还是少。我正在使用Matplotlib的堆叠柱状图。柱子的宽度是根据柱子的数量来决定的。以下是我的示例代码。

我该如何让柱子的宽度保持一致,无论我比较的柱子数量是1个还是10个?

import numpy as np
import matplotlib.pyplot as plt




N =1  
ind = np.arange(N)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence




design = []
arch = []
code = []

fig = plt.figure()



b   = [70]
a= np.array([73])
c = [66]




p1 = plt.bar(ind, a,width, color='#263F6A')
p2 = plt.bar(ind, b, width, color='#3F9AC9', bottom=a)
p3 = plt.bar(ind, c, width, color='#76787A', bottom=a+b)


plt.ylabel('Scores')
plt.title('CQI Index')


plt.xticks(ind+width/2., ('P1'))#dynamic - fed

plt.yticks(np.arange(0,300,15))


plt.legend( (p1[0], p2[0], p3[0]), ('A','B','C') )
plt.grid(True)

plt.show()

谢谢!

1 个回答

2

柱子的宽度是不会改变的,改变的是你图像的比例。如果你希望比例保持不变,就得手动指定你想显示的范围,无论你的图是10x10,100x100,还是1,000,000,000 x 10。

编辑:

如果我理解得没错,你想要的效果大概是这样的:

图1 - 2根柱子:

10
+---------------------------+
|                           |
|                           |
|                           |
|                           |
|                           |
|       4_                  |
|       | |                 |
|  2_   | |                 |
|  | |  | |                 |
|  | |  | |                 |
+---------------------------+ 10

图2 - 再加2根柱子

10
+---------------------------+
|                           |
|                           |
|                 7_        |
|                 | |       |
|                 | |       |
|       4_        | |       |
|       | |  3_   | |       |
|  2_   | |  | |  | |       |
|  | |  | |  | |  | |       |
|  | |  | |  | |  | |       |
+---------------------------+ 10

在图1到图2之间,柱子的明显宽度没有变化。如果你想要这样的效果,就需要设置你图的比例。

你可以用以下方式来做到这一点:

import matplotlib
matplotlib.use('GTKAgg')

import matplotlib.pyplot as plt
import gobject

fig = plt.figure()
ax = fig.add_subplot(111)

def draw1():
    plt.bar(0,2)
    plt.bar(2,4)
    ax.set_xlim((0,10))
    ax.set_ylim((0,10))
    fig.canvas.draw()
    return False

def draw2():
    plt.bar(4,3)
    plt.bar(6,7)

    ax.set_xlim((0,10))
    ax.set_ylim((0,10))
    fig.canvas.draw()
    return False

draw1()
gobject.timeout_add(1000, draw2)
plt.show()

撰写回答