【问题标题】:How to create and empty scatter plot with date on the x axis - Python, Pandas?如何在 x 轴上创建和清空散点图 - Python,Pandas?
【发布时间】:2017-07-29 23:35:57
【问题描述】:

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

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

【问题讨论】:

  • 为什么不在数据框中添加一列来存储每个数据点所需的颜色,然后在绘制数据时将其作为参数color= 传递?

标签: python-3.x pandas datetime matplotlib scatter


【解决方案1】:

您可以在 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()

【讨论】:

    猜你喜欢
    • 2023-01-28
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多