如何在Pandas中实现负数据红线、正数据绿线的折线图?
解决折线图按y值正负切换颜色的问题
看起来你已经找对了方向,但可能在细节上卡壳了。咱们来一步步搞定这个需求:让cum_profit高于0的线段显示绿色,低于0的显示红色,同时保证折线是连续的(不会因为筛选数据而断开)。
先分析你之前尝试的问题
- 首次尝试直接筛选正负值的Series来绘图,这会导致索引不连续,比如当正负值交替出现时,两段折线会因为中间缺失的索引而无法正确连接,看起来像是断开的两段,而不是连续的折线。
- 最新尝试用
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)}) # 模拟你的数据(如果已有df可以跳过这部分) data = { "placed_date": ["2017-07-14 16:06:38", "2017-07-14 16:26:42", "2017-07-14 16:54:53", "2017-07-17 16:48:07", "2017-07-17 18:52:22", "2017-07-17 18:54:51", "2017-07-17 18:59:19", "2017-07-17 19:06:41", "2017-07-17 19:42:42", "2017-07-18 12:46:59"], "cum_profit": [-25.0, -50.0, -75.0, -150.0, -200.0, 10.0, 190.0, 140.0, 90.0, 154.0], "cum_stake": [25, 50, 75, 150, 200, 250, 300, 350, 400, 450] } df = pd.DataFrame(data) # 将日期列转为datetime类型(非常重要,保证x轴是时间序列) df["placed_date"] = pd.to_datetime(df["placed_date"]) # 设置日期为索引,方便时间序列绘图 df.set_index("placed_date", inplace=True) # 绘制正负部分的折线 # 大于等于0的部分用绿色,不符合的设为NaN df["cum_profit"].where(df["cum_profit"] >= 0, np.nan).plot(color='green', linewidth=2, label='Positive Profit') # 小于0的部分用红色,不符合的设为NaN df["cum_profit"].where(df["cum_profit"] < 0, np.nan).plot(color='red', linewidth=2, label='Negative Profit') # 添加图表元素 plt.title('Cumulative Profit Over Time', fontsize=16) plt.xlabel('Date', fontsize=14) plt.ylabel('Cumulative Profit', fontsize=14) plt.legend(fontsize=12) plt.grid(True, alpha=0.3) plt.show()
关键要点解释
- 日期索引处理:一定要把
placed_date转为datetime类型并设为索引,这样matplotlib才能正确渲染时间序列的x轴,避免折线错位。 where方法的作用:df["cum_profit"].where(条件, np.nan)会保留符合条件的值,不符合的替换为NaN。当plot遇到NaN时会自动跳过,这样正负两部分的折线就能在同一个图中连续显示,不会互相干扰。- 共享坐标轴:两次plot默认会共享同一个坐标轴,所以不需要额外设置,就能保证正负折线在同一个时间轴上对齐。
这样运行后,你就能看到cum_profit低于0的部分是红色,高于等于0的部分是绿色,而且折线是连续的,完美符合你的需求~
内容的提问来源于stack exchange,提问作者wazo
相关产品推荐
相关产品推荐

