python - Pandas 中数据为负时为红线,数据为正时为绿线

标签 python pandas matplotlib

我希望该图中的数据在 y 低于 0 时显示为红色,在 y 高于 0 时显示为绿色: profit

我正在尝试这个,但没有成功:

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()

neigh

我的数据如下所示:

+---+---------------------+------------+-----------+
|   |     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()

enter image description here

最佳答案

您遇到的问题是 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()

enter image description here

关于python - Pandas 中数据为负时为红线,数据为正时为绿线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48236622/

相关文章:

python - 看起来相同但编码不同的字符串

python - 如何单独处理由 groupby 创建的组中的第一项?

python - 权限错误 : Permission denied to reading CSV File in Python

python - groupby 操作后简化 pandas 数据框

python - 如何在 python Seaborn 中更改调色板中标签的颜色分配?

python - 按日期时间绘制数据框 按月、年、日分组

python - Python 中的 all(map) 和 any(map) 输出 bool 值,但 IPython 中输出 true 映射对象

python - 是 lambda :function() inside the same function considered recursive?

pandas - 在 Pandas 中使用累积和时,如何填补空白并分配值?

python - 向 matplotlib 等高线图添加十字准线或标记