【问题标题】:matplotlib set stacked bar chart labelsmatplotlib 设置堆叠条形图标签
【发布时间】:2018-06-01 21:13:58
【问题描述】:

我正在尝试创建一个按操作系统对数据进行分组的堆积条形图。我无法为每个栏中的每个组件创建单独的标签。

我要做的与example in the docs 不同,因为在我的数据中,每个类别只出现在一个栏中,而在示例中,每个栏包含每个类别的一个成员。

目前我有这个代码

plt.cla()
plt.clf()
plt.close()

def get_cmap(n, name='hsv'):
    '''Returns a function that maps each index in 0, 1, ..., n-1 to a distinct 
    RGB color; the keyword argument name must be a standard mpl colormap name.'''
    return plt.cm.get_cmap(name, n)

fig = plt.figure(figsize=(18, 10), dpi=80)

# group by the prefixes for now
prefixes = []
indices = []
bars = []
legend = {}
cmap = get_cmap(len(os_counts.index) + 1)
k = 0
for i, prefix in enumerate(d):
    indices.append(i)
    if len(d[prefix]["names"]) == 1:
        prefixes.append(d[prefix]["names"][0])
    else:
        prefixes.append(prefix)
    #colors = [next(cycol) for j in range(len(d[prefix]["names"]))]
    colors = [cmap(k + j) for j in range(len(d[prefix]["names"]))]
    k += len(colors)
    bar = plt.bar([i] * len(d[prefix]["names"]), d[prefix]["values"], color=colors, label=d[prefix]["names"])
    bars.append(bar)


plt.xticks(rotation=90)
plt.ylabel("Frequency")
plt.xlabel("Operating System")
plt.xticks(indices, prefixes)
plt.legend()
plt.show()

这会产生这个结果。如您所见,图例是为条形图中的第一种颜色创建的,并显示一个数组。

【问题讨论】:

    标签: python-3.x matplotlib


    【解决方案1】:

    我认为每次调用 plt.bar 都会获得一个标签。所以,你给它一个列表作为每个 plt.bar 调用的标签。如果您想要每种颜色的标签,代表每种操作系统,那么我认为解决方案是为每种颜色或操作系统调用 plt.bar 一次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      • 1970-01-01
      • 2021-10-22
      • 1970-01-01
      相关资源
      最近更新 更多