如何为 Python 中的每个变量名称制作具有不同宽度和多个值的条形图?

How to make bar plot with varying widths and multiple values for each variable name in Python?

我的问题源于提供的解决方案

在我下面的代码中,我想自动获取变量名称列表,x,并为每个变量分配一种颜色来自颜色映射的变量(例如使用 get_cmap)。我也只希望每个变量在图例中出现一次。在这个例子中,变量 B 和 H 被复制了,我分别为它们分配了 limegreen 和 black。

import matplotlib.pyplot as plt

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

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

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

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

plt.figure(figsize=(20,10))

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)

在这里,我使用 dict 和 zip 来获取 'x' 的单个值,通过导入其他库(如 numpy 或 pandas 有更简单的方法。我们正在做的是基于 this article:

自定义构建 matplotlib 图例
a = plt.bar(xticks, height = y, width = w, color = colors, alpha = 0.8)
_ = plt.xticks(xticks, w)
x, patches = zip(*dict(zip(x, a.patches)).items())
plt.legend(patches, x)

输出:

详情:

  1. 阵容 x a.patches 使用 zip
  2. 使用补丁将每个 x 分配为字典中的键,但字典 密钥是唯一的,所以 x 的补丁将保存到 词典.
  3. 解压字典中项目的元组列表
  4. 将这些作为导入 plt.legend

或者您可以使用:

set_x = sorted(set(x))
xind = [x.index(i) for i in set_x]
set_patches = [a.patches[i] for i in xind]
plt.legend(set_patches, set_x)

使用色图:

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

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

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

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

col_map = plt.get_cmap('tab20')

plt.figure(figsize=(20,10))

xticks=[]
for n, c in enumerate(w):
    xticks.append(sum(w[:n]) + w[n]/2)
    
set_x = sorted(set(x))
xind = [x.index(i) for i in x]
colors = [col_map.colors[i] for i in xind]

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)

set_patches = [a.patches[i] for i in xind]

#x, patches = zip(*dict(zip(x, a.patches)).items())
plt.legend(set_patches, set_x)

输出: