我希望该图中的数据在 y 低于 0 时显示为红色,在 y 高于 0 时显示为绿色:
我正在尝试这个,但没有成功:
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import seaborn as sns
sns.set(rc={"figure.figsize": (20, 10)})
df_positive = df[df["cum_profit"] > 0]["cum_profit"]
df_negative = df[df["cum_profit"] < 0]["cum_profit"]
plt.plot(df_positive, color='green')
plt.plot(df_negative, color='red')
plt.show()
我的数据如下所示:
+---+---------------------+------------+-----------+
| | placed_date | cum_profit | cum_stake |
+---+---------------------+------------+-----------+
| 0 | 2017-07-14 16:06:38 | -25.0 | 25 |
| 1 | 2017-07-14 16:26:42 | -50.0 | 50 |
| 2 | 2017-07-14 16:54:53 | -75.0 | 75 |
| 3 | 2017-07-17 16:48:07 | -150.0 | 150 |
| 4 | 2017-07-17 18:52:22 | -200.0 | 200 |
| 5 | 2017-07-17 18:54:51 | 10.0 | 250 |
| 6 | 2017-07-17 18:59:19 | 190.0 | 300 |
| 7 | 2017-07-17 19:06:41 | 140.0 | 350 |
| 8 | 2017-07-17 19:42:42 | 90.0 | 400 |
| 9 | 2017-07-18 12:46:59 | 154.0 | 450 |
+---+---------------------+------------+-----------+
更新 最新尝试:
#df["positive"] = np.where(df["cum_profit"] > 0, df["cum_profit"], None)
#df["negative"] = np.where(df["cum_profit"] < 0, df["cum_profit"], None)
df.cum_profit.where(df.cum_profit.ge(0), np.nan).plot(color='green')
df.cum_profit.where(df.cum_profit.lt(0), np.nan).plot(color='red')
#plt.plot(df["positive"] , color='green')
#plt.plot(df["negative"], color='red')
plt.show()
最佳答案
您遇到的问题是 matplotlib 将绘制一条连接每个连续可绘制点的线。通过对数据框进行切片,您仍然可以提供所有可绘制的点,只是带有一个间隔索引。
为了解决这个问题,您可以在绘图操作中包含不可绘制的点。使用 .where()
并将填充值设置为 NaN
,而不是切片。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(rc={"figure.figsize": (20, 10)})
np.random.seed(200)
df = pd.DataFrame(np.cumsum(np.random.rand(10000)-0.5), columns=['cum_profit'])
df.cum_profit.where(df.cum_profit.ge(0), np.nan).plot(color='green')
df.cum_profit.where(df.cum_profit.lt(0), np.nan).plot(color='red')
plt.show()
关于python - Pandas 中数据为负时为红线,数据为正时为绿线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48236622/