在matplotlib pyplot中,如何按类别对条形图中的条进行分组?

时间:2020-06-26 09:16:16

标签: python matplotlib plot categorical-data

首先,我不是要制作常规的分组条形图。

我有两个数组,例如

user_score = [70, 95, 86, 50, 17]
user_type = ['High', 'High', 'High', 'Mid', 'Low']

我正在尝试创建一个条形图,以使同一类别的条形(在这种情况下为user_type)通过分隔或颜色分组在一起。

我要实现的目标示例图片

图。 1

如何在pyplot中执行此操作?

目前,对于我的实际用例,我只能实现:

图。 2

编辑:

1。

实际数据:

user_utilisation_rating = [0.0, 0.0, 0.0, 0.06, 0.09, 0.12, 0.13, 0.13, 0.14, 0.14, 0.16, 0.26, 0.3, 0.53, 0.54, 0.56, 0.76, 0.79, 1.0, 1.0]
user_type = ['Minimum', 'Minimum', 'Minimum', 'Consistent low', 'Consistent low', 'Consistent low', 'Consistent low', 'Consistent low', 'Consistent low', 'Consistent low', 'Consistent low', 'Ending low', 'Ending low', 'Start low', 'Start low', 'Start low', 'Consistent high', 'Consistent high', 'Maximum', 'Maximum']

2。

将图1更改为样式,使其与图2中的实际图更相似。

3。

尝试以此完成任务,但是每个user_type仅显示1条。不知道我在做什么错。

import pandas as pd

user_pd = pd.DataFrame({
    'utilisation' : users_utilisation_rating,
    'type' : user_type
})

user_pd.sort_values(by=['utilisation'], inplace=True)

fig, ax = plt.subplots(figsize = (14, 10))

for tp in user_pd['type'].unique():
    ax.bar(user_pd[user_pd['type'] == tp]['type'],
           user_pd[user_pd['type'] == tp]['utilisation'],
           label = tp)

ax.legend()
plt.show()

2 个答案:

答案 0 :(得分:2)

您可以像这样在'cylinders'列中循环访问唯一元素:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv('mpg.csv')
df.sort_values(by = ['cylinders', 'mpg'], inplace = True)

fig, ax = plt.subplots(figsize = (14, 10))

for cyl in df['cylinders'].unique():
    ax.bar(df[df['cylinders'] == cyl]['name'],
           df[df['cylinders'] == cyl]['mpg'],
           label = cyl)
plt.setp(ax.xaxis.get_majorticklabels(), rotation = 90)
ax.legend()

plt.show()

并获得此图:

enter image description here


或者您可以使用seaborn.barplot

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

df = pd.read_csv('mpg.csv')
df.sort_values(by = ['cylinders', 'mpg'], inplace = True)

fig, ax = plt.subplots(figsize = (14, 10))

sns.barplot(x = df['name'],
            y = df['mpg'],
            hue = df['cylinders'],
            dodge = False)
plt.setp(ax.xaxis.get_majorticklabels(), rotation = 90)

plt.show()

并获得此图:

enter image description here


最后,如果您想稍微改善一下条形,可以使用透明度值:

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

df = pd.read_csv('mpg.csv')
df.sort_values(by = ['cylinders', 'mpg'], inplace = True)

fig, ax = plt.subplots(figsize = (14, 10))

sns.barplot(x = df['name'],
            y = df['mpg'],
            hue = df['cylinders'],
            edgecolor = 'k',
            dodge = False,
            alpha = 0.3)
plt.setp(ax.xaxis.get_majorticklabels(), rotation = 90)

plt.show()

给出:

enter image description here

答案 1 :(得分:2)

根据您的数据,您可以执行以下操作:

color_map = {"Start low": "#581845",
            "Consistent low": "#900C3F",
            "Ending low":"#C70039",
            "Minimum":"#FF5733",
            "Consistent high":"#FFC300",
            "Maximum":"#509916"}


df = pd.DataFrame({"user_rating": user_utilisation_rating,
                  "user_type": user_type})
df.plot.bar(x='user_type', y='user_rating', rot=45,
          color=[color_map[i] for i in user_type])
plt.legend().remove()
plt.show()

产生以下内容: enter image description here

注意:请注意,由于x轴起了作用,因此我删除了图例