【问题标题】:How to merge line graph with grouped bar chart with annotation如何将折线图与带注释的分组条形图合并
【发布时间】:2020-04-25 17:18:14
【问题描述】:

我有一个非常大的 excel 文件。我从那里调整了这些值:

      Month       Task         baseline  Total Ownership
Team       Caterpillar Infosys
4      Jan        2273    7417     6000   9690     76.54%
3      Feb        2372    7222     6000   9594     75.28%
7      Mar        2624    8088     6000  10712     75.50%
0      Apr        2418    7993     6000  10411     76.77%
8      May        2891    7865     6000  10756     73.12%
6      Jun        1950    7182     6000   9132     78.65%
5      Jul        2027    7858     6000   9885     79.49%
1      Aug        1804    7259     6000   9063     80.09%
11     Sep        1708    7558     6000   9266     81.57%
10     Oct        2482    8601     6000  11083     77.61%
9      Nov        2137    8037     6000  10174     79.00%
2      Dec        1407    7168     6000   8575     83.59%

我想要一个分组条形图,在 x 轴上有月份,在 y 轴上有任务,每个条形的顶部都有值,并且在所有权的次要 y 轴上有一个折线图,其中有每个月的值。

我已经写了这段代码:

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import matplotlib.ticker as mtick
import seaborn as sns

df = pd.read_excel(r'C:\Users\patelmk1\Downloads\Automation\Incident Data _1231.xlsx')
pivot = df[df['Team'] != 'Autocloser'].pivot_table(index='Month', columns='Team',
                    aggfunc={'Task': pd.Series.count})
pivot.reset_index(inplace = True)
pivot['baseline'] = 6000
pivot['Total'] = pivot['Task']['Infosys'] + pivot['Task']['Caterpillar']
pivot['Ownership'] = pivot['Task']['Infosys'] / pivot['Total']
pivot['Ownership'] = pivot['Ownership'].map('{:.2%}'.format)
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", 
          "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
pivot['Month'] = pd.Categorical(pivot['Month'], categories=months, ordered=True)
pivot.sort_values('Month', inplace = True)
print(pivot)
x = np.arange(len(pivot['Month']))
width = 0.35  # the width of the bars

fig, ax = plt.subplots(figsize = (15,7))
ax.set_xticks(x)
ax.set_xticklabels(pivot['Month'])
ax2 = ax.twinx()
ax2.set_ylim(bottom = 0, top = 100)
ax2.yaxis.set_major_formatter(mtick.PercentFormatter())
ax2.plot(ax.get_xticks(), pivot['Ownership'], marker = 'o')
rects1 = ax.bar(x - width/2, pivot['Task']['Caterpillar'], width, label='Caterpillar')
rects2 = ax.bar(x + width/2, pivot['Task']['Infosys'], width, label='Infosys')

ax.legend()
ax.plot(pivot['baseline'])
ax.set_title("Overall")

def autolabel(rects):
    """Attach a text label above each bar in *rects*, displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')


autolabel(rects1)
autolabel(rects2)

fig.tight_layout()
plt.savefig('fig.png')
plt.show()

这是我得到的图表:

这就是我想要绘制的:

【问题讨论】:

  • 你想要的输出是什么?你想以什么方式组合这些情节?
  • 我已经编辑了我的问题。

标签: python pandas matplotlib seaborn


【解决方案1】:

您的问题是Ownership 列中的值是字符串,它们应该是要绘制的数字

删除

pivot['Ownership'] = pivot['Task']['Infosys'] / pivot['Total']
pivot['Ownership'] = pivot['Ownership'].map('{:.2%}'.format)

改为写

pivot['Ownership'] = 100 * pivot['Task']['Infosys'] / pivot['Total']

【讨论】:

  • 谢谢.. 我不知道即使我将值格式化为小数点后两位数,它也会转换为字符串。
  • 不客气。如果这解决了您的问题,请考虑接受左侧带有复选标记的答案,以将此主题标记为已关闭
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多