如何创建和清空 x 轴上带有日期的散点图 - Python、Pandas?

How to create and empty scatter plot with date on the x axis - Python, Pandas?

我有一个如下所示的数据框:

date                  number_of_books   ... (additional columns)
1997/06/01 23:15        3
1999/02/19 14:56        5
1999/10/22 18:20        7 
2001/11/04 19:13        19
...                     ...
2014/04/30 02:14        134

我的目标是创建一个空的散点图,然后分别添加每个点,因为点的颜色取决于数据框中的其他因素。但是,我无法找到一种方法来创建空散点图而不使用我的数据框。有没有办法做到这一点? (可能通过让一个变量来保存情节?)我希望 x 轴只是日期(YYYY/MM/DD),y 轴是书的数量。

我的计划是在将日期字符串和 number_of_book 字符串添加到绘图之前转换它们。所以这个想法是...

for index, row in df.itterows()
    convert date to datetime and number_of_books to int
    if condition met (based on other columns):
         plot with color blue
    else:
         plot with color red

您可以在 pd.DataFrame 中创建一个列来存储颜色信息,并使用 scatter 绘图函数将参数传递给每个数据点。

参见示例:

import pandas as pd
import matplotlib.pyplot as plt

# your dataframe
df = pd.DataFrame({"date": ["1997/06/01 23:15", "1999/02/19 14:56", "1999/10/22 18:20", "2001/11/04 19:13"],
                    "number_of_books": [3, 5, 7, 19]})

# add empty column to store colors
df["color"] = np.nan

# loop over each row and attribute a conditional color
for row in range(len(df)):
    if row<2: #put your condition here
        df.loc[row, "color"] = "r"
    else: #second condition here
        df.loc[row, "color"] = "b"

# convert the date column to Datetime
df.date = pd.to_datetime(df.date)

# plot the data
plt.scatter([x for x in df.date], df.number_of_books, c=df.color)
plt.show()