我正在创建一个分组的条形图,其中,各组基于百分比降序显示。我需要能够分别标记组中的两个条形,如下所示:
到目前为止,这是我的代码,任何指向我正确方向的东西都会有所帮助:
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()
此代码似乎是您要的内容:
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()