Matplotlib中的群集柱形图的绘制

时间:2020-09-05 18:49:51

标签: python matplotlib bar-chart seaborn

任何人都可以解释如何在Matplotlib中完全像这样绘制群集柱形图吗?我找到了一些类似的图形,但是我想要的是如图所示的图形。我将诸如苹果和梨等水果名称作为密钥,并将它们在几年中的销售作为这些密钥的值。

enter image description here

1 个答案:

答案 0 :(得分:0)

以下代码首先创建一些玩具数据,然后使用matplotlib绘制条形图。

5

example plot

在此示例中,数据如下:

import matplotlib.pyplot as plt
from matplotlib.transforms import blended_transform_factory
from matplotlib.ticker import MultipleLocator
import numpy as np
import pandas as pd
import seaborn as sns

fruits = ['apples', 'pears', 'nectarines', 'plums', 'grapes', 'strawberries']
years = [2015, 2016, 2017]
num_fruit = len(fruits)
num_years = len(years)
df = pd.DataFrame({'fruit': np.tile(fruits, num_years),
                   'year': np.repeat(years, num_fruit),
                   'value': np.random.randint(1, 8, num_fruit * num_years)})

width = 0.8
for i, fruit in enumerate(fruits):
    for j, year in enumerate(years):
        plt.bar(i + width / num_years * (j - (num_years - 1) / 2),
                df[(df['fruit'] == fruit) & (df['year'] == year)]['value'],
                width / num_years, color='skyblue', ec='white')
plt.xticks([i + width / num_years * (j - (num_years - 1) / 2) for i in range(num_fruit) for j in range(num_years)],
           np.tile(years, num_fruit), rotation=45)
ax = plt.gca()
ax.yaxis.set_major_locator(MultipleLocator(1))
ax.yaxis.set_minor_locator(MultipleLocator(0.2))
ax.grid(True, axis='y')
ax.autoscale(False, axis='y')
trans = blended_transform_factory(ax.transData, ax.transAxes)
for i, fruit in enumerate(fruits):
    ax.text(i, -0.2, fruit, transform=trans, ha='center')
    if i != 0:
        ax.vlines(i - 0.5, 0, -0.3, color='lightgrey', clip_on=False, transform=trans)
plt.tight_layout()
print(df)
plt.show()