带值总和的绘图日期

时间:2019-05-21 19:41:36

标签: python matplotlib

我想绘制数据框的日期以及该日期发生的I或O的数量。例如,如果我们在05/18/2019总共有100个I,则该日期的x轴为05/18/2019,y轴为100。

我曾尝试使用value_counts()和其他类型的绘图进行绘图,但没有获得如上所述的所需内容。这是我拥有的数据的一部分。第一列是索引,第二列是日期,第三列是I。

0   2019-05-18  I
1   2019-05-18  I
2   2019-05-18  I
3   2019-05-18  I
4   2019-05-18  I
5   2019-05-18  I
6   2019-05-17  I
7   2019-05-17  I
8   2019-05-17  I
9   2019-05-17  I
10  2019-05-17  I
11  2019-05-17  I
12  2019-05-17  I
13  2019-05-17  I
14  2019-05-16  I
15  2019-05-16  I
16  2019-05-16  I
17  2019-05-16  I
18  2019-05-16  I

2 个答案:

答案 0 :(得分:0)

您要查找分组依据和计数。

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

df = pd.DataFrame({'date': ['18-05-2019', '18-05-2019', '19-05-2019', '19-05-2019'], 'is_i': ['I', 'O', 'I', 'U']})
df['date'] = pd.to_datetime(df['date'], format='%d-%m-%Y')

# Groupby for counts - filter however you want
counts_df = df[df['is_i'].isin(['I', 'O'])].groupby('date').count()

# Plot
fig, ax = plt.subplots()
ax.plot(counts_df.index, counts_df['is_i'])

# Format x ticks
datesFmt = mdates.DateFormatter('%d-%m-%Y')
ax.xaxis.set_major_formatter(datesFmt)
ax.set_xticks(counts_df.index)

plt.show()

Plot with reasonable xticks

答案 1 :(得分:0)

这是创建堆积条形图的解决方案

import pandas as pd 
import matplotlib.pyplot as plt

dict = { "date": ["2019-05-18", "2019-05-18","2019-05-18","2019-05-18","2019-05-18",
                  "2019-05-18","2019-05-17","2019-05-17","2019-05-17","2019-05-17",
                  "2019-05-17","2019-05-17","2019-05-17","2019-05-17","2019-05-16",
                  "2019-05-16","2019-05-16","2019-05-16","2019-05-16"],
          "letter" : ["I","I", "O","I","O","I","I","I","I","I","I","I","I","O","I","I", "O", "O", "O"] }

df = pd.DataFrame(dict)

df_count = pd.crosstab(df["date"], df["letter"])

df_count.plot.bar(stacked=True)
plt.legend(title='Counts')
plt.ylabel('Date')
plt.show()