簡體   English   中英

如何將 plot 和 pandas dataframe 列作為數據,另一列作為顏色編號?

[英]How to plot a pandas dataframe with one column as data and the other column as color number?

我正在嘗試根據不同的標簽制作彩色 plot 。 這是 dataframe df。

Date                Close     label
2007-09-18 00:00:00 4546.200195 2
2007-09-19 00:00:00 4732.350098 2
2007-09-20 00:00:00 4747.549805 2
2007-09-21 00:00:00 4837.549805 2
2007-09-24 00:00:00 4932.200195 2
... ... ...
2010-09-24 00:00:00 6018.299805 2
2010-09-27 00:00:00 6035.649902 2
2010-09-28 00:00:00 6029.500000 2
2010-09-29 00:00:00 5991.299805 1
2010-09-30 00:00:00 6029.950195 1

我知道如何使用plt.scatter() plot 它,但我必須提供范圍索引,以便 x 軸充滿數字。 我想 plot 這個數據看起來與我的 plot 類似藍色表示 2),它的 x 軸為日期,這是 dataframe = df.index 的索引。

我將從label列和 plot 每個點用特定顏色制作一個顏色數組。

# If you want Date column as index, add the following lines
# df['Date'] = pd.to_datetime(df['Date'])
# df.set_index('Date', inplace=True)


plot = df['Close'].plot()

xs = df.index
ys = df['Close']
colors = df['label'].replace({1: 'red', 2: 'blue'})

for x, y, c in zip(xs, ys, colors):
    plt.scatter(x, y, color=c)

plt.show()

在此處輸入圖像描述

import matplotlib.pyplot as plt
import pandas as pd
%matplotlib inline

my_series = {
'Date': {0: '2021-03-28', 1: '2021-03-29', 2: '2021-03-30'},
'Close': {0: 1000, 1: 1100, 2: 1200},
'label': {0: 1,1: 2,2: 3}
}

colors = ['black', 'blue', 'red', 'green']

df = pd.DataFrame(my_series)
df['color'] = df.apply(lambda row: colors[row.label], axis=1)
plt.scatter(df['Date'], df['Close'], c= df['color'])

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM