拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 如何在Python中绘制宽度可变但没有间隙的条形图,并将条形宽度添加为x轴上的标签?

如何在Python中绘制宽度可变但没有间隙的条形图,并将条形宽度添加为x轴上的标签?

白鹭 - 2022-03-15 2161 0 0

我有三个串列:x、y 和 w,如图所示:x 是物件的名称。y 是它的高度,w 是它的宽度。

x = ["A","B","C","D","E","F","G","H"]

y = [-25, -10, 5, 10, 30, 40, 50, 60]

w = [30, 20, 25, 40, 20, 40, 40, 30]

我想在 Python 的条形图中绘制这些值,这样 y 代表高度,w 代表条形的宽度。

当我绘制它使用

colors = ["yellow","limegreen","green","blue","red","brown","grey","black"]

plt.bar(x, height = y, width = w, color = colors, alpha = 0.8)

我得到一个如图所示的情节: 如何在 Python 中绘制宽度可变但没有间隙的条形图,并将条形宽度添加为 x 轴上的标签?

接下来,我尝试标准化宽度,以便使用条形图不会相互重叠

w_new = [i/max(w) for i in w]
plt.bar(x, height = y, width = w_new, color = colors, alpha = 0.8)
#plt.axvline(x = ?)
plt.xlim((-0.5, 7.5))

如图所示,我得到了比以前更好的结果: 如何在 Python 中绘制宽度可变但没有间隙的条形图,并将条形宽度添加为 x 轴上的标签?

但是,条形之间的间隙仍然不均匀。比如B和C之间,差距很大。但F和G之间,没有差距。

我想要在两个连续条之间有均匀间隙宽度或没有间隙的图。它看起来应该如图所示:如何在 Python 中绘制宽度可变但没有间隙的条形图,并将条形宽度添加为 x 轴上的标签?

如何在 Python 中创建这种型别的图?是否可以使用任何资料可视化库,例如 matplotlib、seaborn 或 Plotly?如果资料在资料框中可用,是否还有其他选择?

此外,我想在图的右侧添加 A、B、C 等的标签,而是将条的实际宽度作为 x 轴上的标签(例如,在 x-上面的轴图)。我还想在距离 x 轴 50 处添加一条垂直红线。我知道这可以使用添加plt.axvline(x = ...)但我不确定我应该宣告为 x 的值是多少,因为 W 的比例与 x 轴的长度不准确。

uj5u.com热心网友回复:

IIUC,你可以试试这样的:

import matplotlib.pyplot as plt

x = ["A","B","C","D","E","F","G","H"]

y = [-25, -10, 5, 10, 30, 40, 50, 60]

w = [30, 20, 25, 40, 20, 40, 40, 30]

colors = ["yellow","limegreen","green","blue","red","brown","grey","black"]

#plt.bar(x, height = y, width = w, color = colors, alpha = 0.8)

xticks=[]
for n, c in enumerate(w):
    xticks.append(sum(w[:n])   w[n]/2)
    
w_new = [i/max(w) for i in w]
a = plt.bar(xticks, height = y, width = w, color = colors, alpha = 0.8)
_ = plt.xticks(xticks, x)

plt.legend(a.patches, x)

输出:

如何在 Python 中绘制宽度可变但没有间隙的条形图,并将条形宽度添加为 x 轴上的标签?

或更改条形宽度的 xticklabels:

xticks=[]
for n, c in enumerate(w):
    xticks.append(sum(w[:n])   w[n]/2)
    
w_new = [i/max(w) for i in w]
a = plt.bar(xticks, height = y, width = w, color = colors, alpha = 0.8)
_ = plt.xticks(xticks, w)
plt.legend(a.patches, x)

输出:

如何在 Python 中绘制宽度可变但没有间隙的条形图,并将条形宽度添加为 x 轴上的标签?

uj5u.com热心网友回复:

我想出了另一种方法来做到这一点。

x = ["A","B","C","D","E","F","G","H"]

y = [-25, -10, 5, 10, 30, 40, 50, 60]

w = [30, 20, 25, 40, 20, 40, 40, 30]

xpos = []

a = 0
for i in range(len(w)):
    if i == 0:
        a =w[i]
       
        xpos.append(w[i]/2)
        
    else:
        a  = w[i]
       
        xpos.append(a - w[i]/2)

colors = ["yellow","limegreen","green","blue","red","brown","grey","black"]


fig = plt.bar(xpos,
        height = y,
        width = w,
        color = colors,
        alpha = 0.5,
      )

plt.xticks(ticks = xpos, labels = w)

plt.xlim((0, 245))
plt.axvline(x = 150)
plt.legend(fig.patches, x)

plt.show()

如何在 Python 中绘制宽度可变但没有间隙的条形图,并将条形宽度添加为 x 轴上的标签?

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *