用次轴线图制作分类或分组条形图

2024-09-21 03:16:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要比较4个班次(分类/分组)之间不同的每日数据集,使用条形图和折线图。我到处找遍了,没有找到一个有效的解决方案,不包括生成新的支点等等。在

我同时使用了matplotlib和seaborn,虽然我可以做一个或另一个(每个班次有不同颜色的条/线),但一旦我合并了另一个,要么其中一个消失了,要么其他异常情况发生,就像只有一个绘图点显示的那样。我已经看了所有的地方,有解决方案来表示单一系列的数据在两种图表类型,但没有一个进入多类别或分组为两种类型。在

数据示例:

report_date wh_id   shift   Head_Count  UTL_R
3/17/19     55  A   72  25%
3/18/19     55  A   71  10%
3/19/19     55  A   76  20%
3/20/19     55  A   59  33%
3/21/19     55  A   65  10%
3/22/19     55  A   54  20%
3/23/19     55  A   66  14%
3/17/19     55  1   11  10%
3/17/19     55  2   27  13%
3/17/19     55  3   18  25%
3/18/19     55  1   23  100%
3/18/19     55  2   16  25%
3/18/19     55  3   12  50%
3/19/19     55  1   28  10%
3/19/19     55  2   23  50%
3/19/19     55  3   14  33%
3/20/19     55  1   29  25%
3/20/19     55  2   29  25%
3/20/19     55  3   10  50%
3/21/19     55  1   17  20%
3/21/19     55  2   29  14%
3/21/19     55  3   30  17%
3/22/19     55  1   12  14%
3/22/19     55  2   10  100%
3/22/19     55  3   17  14%
3/23/19     55  1   16  10%
3/23/19     55  2   11  100%
3/23/19     55  3   13  10%
^{pr2}$

这段代码让我离得最近。请注意,即使使用stacked = False,它们仍然是堆叠的。我把设置改为真,什么也没变。在

所有我需要的是,酒吧是相邻的,以相同的颜色方案代表的变化

图表:

graph


Tags: 数据绘图类型matplotlib颜色图表分类seaborn
2条回答

这里有两个解决方案(堆叠和未堆叠)。根据您的问题,我们将:

  • 在左y轴绘制Head_Count,在右y轴绘制UTL_R。在
  • report_date将是我们的x轴
  • shift将代表图形的色调。在

堆叠版本使用pandas默认打印功能,未堆叠版本使用seaborn。在


根据你的要求,我添加了一个100%堆积图。虽然它不完全是您在注释中要求的,但是您所要求的图形类型在读取时可能会造成一些混乱(这些值是基于堆栈的上行或堆栈的宽度)。另一种解决方案是使用100%堆积图。在

堆叠

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

dfg = df.set_index(['report_date', 'shift']).sort_index(level=[0,1])

fig, ax = plt.subplots(figsize=(12,6))

ax2  = ax.twinx()

dfg['Head_Count'].unstack().plot.bar(stacked=True, ax=ax, alpha=0.6)
dfg['UTL_R'].unstack().plot(kind='line', ax=ax2, marker='o', legend=None)

ax.set_title('My Graph')
plt.show()

enter image description here

100%堆积

^{pr2}$

enter image description here

未堆叠

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

dfg = df.set_index(['report_date', 'shift']).sort_index(level=[0,1])

fig, ax = plt.subplots(figsize=(15,6))

ax2  = ax.twinx()

sns.barplot(x=dfg.index.get_level_values('report_date'),
            y=dfg.Head_Count,
           hue=dfg.index.get_level_values('shift'), ax=ax, alpha=0.7)

sns.lineplot(x=dfg.index.get_level_values('report_date'),
            y=dfg.UTL_R,
           hue=dfg.index.get_level_values('shift'), ax=ax2, marker='o', legend=None)

ax.set_title('My Graph')
plt.show()

enter image description here


编辑2

这是您第二次请求的图形(堆栈,但堆栈n+1不是从堆栈n结束的位置开始的)。在

因为我们要做很多事情,所以它的参与程度要稍微高一些: -我们需要手动为df中的shift指定颜色 -一旦我们分配了颜色,我们将迭代每个日期范围和1)排序或Head_Count值降序(以便我们在绘制图形时最大的sack在后面),2)绘制数据并将颜色分配给每个stacj -然后我们可以创建第二个y轴并绘制UTL_R值 -然后我们需要为图例标签指定正确的颜色

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

def assignColor(shift):
    if shift == 'A':
        return 'R'
    if shift == '1':
        return 'B'
    if shift == '2':
        return 'G'
    if shift == '3':
        return 'Y'

# map a color to a shift
df['color'] = df['shift'].apply(assignColor)

fig, ax = plt.subplots(figsize=(15,6))

# plot our Head_Count values
for date in df.report_date.unique():
    d = df[df.report_date == date].sort_values(by='Head_Count', ascending=False)
    y = d.Head_Count.values
    x = date
    color = d.color
    b = plt.bar(x,y, color=color)

# Plot our UTL_R values
ax2 = ax.twinx()    

sns.lineplot(x=df.report_date, y=df.UTL_R, hue=df['shift'], marker='o', legend=None)

# Assign the color label color to our legend
leg = ax.legend(labels=df['shift'].unique(), loc=1)

legend_maping = dict()

for shift in df['shift'].unique():
    legend_maping[shift] = df[df['shift'] == shift].color.unique()[0]

i = 0
for leg_lab in leg.texts:
    leg.legendHandles[i].set_color(legend_maping[leg_lab.get_text()])
    i += 1

enter image description here

这个怎么样?在

tm_daily_df['UTL_R'] = tm_daily_df['UTL_R'].str.replace('%', '').astype('float') / 100
pivoted = tm_daily_df.pivot_table(values=['Head_Count', 'UTL_R'], 
                                  index='report_date', 
                                  columns='shift')
pivoted

#             Head_Count             UTL_R
# shift                1   2   3   A     1     2     3     A
# report_date
# 3/17/19             11  27  18  72  0.10  0.13  0.25  0.25
# 3/18/19             23  16  12  71  1.00  0.25  0.50  0.10
# 3/19/19             28  23  14  76  0.10  0.50  0.33  0.20
# 3/20/19             29  29  10  59  0.25  0.25  0.50  0.33
# 3/21/19             17  29  30  65  0.20  0.14  0.17  0.10
# 3/22/19             12  10  17  54  0.14  1.00  0.14  0.20
# 3/23/19             16  11  13  66  0.10  1.00  0.10  0.14

fig, ax = plt.subplots()
pivoted['Head_Count'].plot.bar(ax=ax)
pivoted['UTL_R'].plot.line(ax=ax, legend=False, secondary_y=True, marker='D')
ax.legend(loc='upper left', title='shift')

相关问题 更多 >

    热门问题