首页 > 解决方案 > Matplotlib,绘制数据框的列,线条根据另一列的条件改变颜色

问题描述

基本上我有一个看起来像这样的熊猫数据框:

                time    price   trend   related_price
1   2019-10-23 15:00:01 6748.9  no trend    
2   2019-10-23 15:00:02 6749.1  increasing  6749.1  
3   2019-10-23 15:00:03 6749.0  no trend    
4   2019-10-23 15:00:04 6749.0  no trend    
5   2019-10-23 15:00:05 6748.0  decreasing  6748
6   2019-10-23 15:00:06 6749.0  no trend    

我想要的是随着时间的推移绘制列价格,当列趋势变为时increasing,线价格变为绿色,当列趋势变为时decreasing,线价格变为红色。我浏览了文档,但没有找到任何方法,有什么线索吗?谢谢!

标签: pythonpandasmatplotlib

解决方案


我不确定这是否是最优雅的方式,因为我对 Python 还很陌生,但这似乎可以满足您的需求。

一、导入相关库:

import pandas as pd
import matplotlib.pyplot as plt

然后,将所有价格数据绘制为一条黑线:

plt.plot(df['time'], df['price'], c = 'k')

最后,遍历价格列的连续行的组合(因为这确实是您想要进行颜色编码的内容,而不是点本身)。此处的代码将识别每个连续元素组合中的第二个元素是否类似于增加或减少。如果是增加,它将在黑线的那段上绘制一条绿线。相反,如果它是减少,它将在黑线的那段上绘制一条红线。

for val in range(2, len(df)+1):   
    start = val - 2
    focal_val = val -1
    if df['trend'][focal_val] == 'increasing':
        plt.plot(df['time'][start:val], df['price'][start:val], c = 'g')
    elif df['trend'][focal_val] == 'decreasing':
        plt.plot(df['time'][start:val], df['price'][start:val], c = 'r')

最终的图表如下 所示


推荐阅读