试试这个:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
A = pd.DataFrame(columns=["Date", "Headlines"], data=[["01/03/2018","Cricket"],["01/03/2018","Football"],
["02/03/2018","Football"],["01/03/2018","Football"],
["02/03/2018","Cricket"],["02/03/2018","Cricket"]] )
您的数据如下所示:
print (A)
Date Headlines
0 01/03/2018 Cricket
1 01/03/2018 Football
2 02/03/2018 Football
3 01/03/2018 Football
4 02/03/2018 Cricket
5 02/03/2018 Cricket
现在对其进行分组操作:
data = A.groupby(["Date","Headlines"]).size()
print(data)
Date Headlines
01/03/2018 Cricket 1
Football 2
02/03/2018 Cricket 2
Football 1
dtype: int64
您现在可以使用以下代码对其进行绘制:
# set width of bar
barWidth = 0.25
# set height of bar
bars1 = data.loc[(data.index.get_level_values('Headlines') =="Cricket")].values
bars2 = data.loc[(data.index.get_level_values('Headlines') =="Football")].values
# Set position of bar on X axis
r1 = np.arange(len(bars1))
r2 = [x + barWidth for x in r1]
# Make the plot
plt.bar(r1, bars1, color='#7f6d5f', width=barWidth, edgecolor='white', label='Cricket')
plt.bar(r2, bars2, color='#557f2d', width=barWidth, edgecolor='white', label='Football')
# Add xticks on the middle of the group bars
plt.xlabel('group', fontweight='bold')
plt.xticks([r + barWidth for r in range(len(bars1))], data.index.get_level_values('Date').unique())
# Create legend & Show graphic
plt.legend()
plt.xlabel("Date")
plt.ylabel("Count")
plt.show()
希望这会有所帮助!