使用matplotlib为组中的条形图创建带有xtick标签的分组条形图

问题描述 投票:0回答:1

我正在创建一个分组的条形图,其中,各组基于百分比降序显示。我需要能够分别标记组中的两个条形,如下所示:What I need

然而,到目前为止,我只能在网上找到代码:What I have

到目前为止,这是我的代码,任何指向我正确方向的东西都会有所帮助:

products = ['chew', 'e_cigarette', 'cigarette', 'hookah', 'cigar']
def make_a_graph(products, per_totals, per_users):
  per_totals.sort(reverse = True)
  per_users.sort(reverse = True)
  n_groups = len(products)

  fig, ax = plt.subplots()
  index = np.arange(n_groups)
  bar_width = 0.4

  totals = plt.bar(index - bar_width/2, per_totals, bar_width, color = 'b', label = '% of All Students')

  users = plt.bar(index + bar_width/2, per_users, bar_width, color = 'lightblue', label = '% of Product Users')

  plt.xlabel('Tobacco Product')
  plt.ylabel('Percent of Users')
  plt.title('Figure 2. Tobacco Use for 16-18 Year Olds')
  plt.legend()

  plt.tight_layout()
  plt.show()
matplotlib label grouping bar-chart
1个回答
0
投票

此代码似乎是您要的内容:

import matplotlib.pyplot as plt
import numpy as np

products = ['chew', 'e_cigarette', 'cigarette', 'hookah', 'cigar']

per_totals = [3, 2, 1, 7, 1]
per_users = [16, 31, 26, 37, 20]

per_totals, products_totals = zip(*sorted(zip(per_totals, products), reverse=True))
per_users, products_users = zip(*sorted(zip(per_users, products), reverse=True))

n_groups = len(products)

fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.4

print(np.append(index - bar_width/2, index + bar_width/2))
totals = plt.bar(index - bar_width/2, per_totals, bar_width, color = '#2c7fb8', label = '% of All Students')

users = plt.bar(index + bar_width/2, per_users, bar_width, color = '#7fcdbb', label = '% of Product Users')

plt.xticks(np.append(index - bar_width/2, index + bar_width/2), products_totals+products_users, rotation=20)

plt.xlabel('Tobacco Product')
plt.ylabel('Percent of Users')
plt.title('Figure 2. Tobacco Use for 16-18 Year Olds')
plt.legend()

plt.tight_layout()
plt.show()

resulting plot

© www.soinside.com 2019 - 2024. All rights reserved.