Pyplot - 如果数据小于零,改变线条的颜色? [英] Pyplot - change color of line if data is less than zero?

查看:31
本文介绍了Pyplot - 如果数据小于零,改变线条的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚pyplot中是否有任何内置的东西会根据数据是负数还是正数来改变我的线条的颜色.例如,如果值为负,我希望线条为红色,如果值为正,我希望线条为不同的颜色,例如黑色.

I am trying to figure out if there is anything built into pyplot that will change the color of my line depending on whether or not the data is negative or positive. For example, if it is negative I'd like the line to be red and if it's positive I'd like the line to be a different color, say black.

图书馆里有什么东西可以让我这样做吗?我想到的一件事是将数据分成两组正面和负面并分别绘制它们,但我想知道是否有更好的方法.

Is there anything in the library that lets me do this? One thing I've thought of is to split the data into two sets of positive and negative and plotting them separately but I'm wondering if there is a better way.

推荐答案

我只想制作两个数据集并设置正确的掩码.通过使用这种方法,我不会在不同的积极因素之间划清界限部分.

I would just make two datasets and setting the right masks. By using that approach i wont have lines between different positive parts.

import matplotlib.pyplot as plt
import numpy as np

signal = 1.2*np.sin(np.linspace(0, 30, 2000))
pos_signal = signal.copy()
neg_signal = signal.copy()

pos_signal[pos_signal <= 0] = np.nan
neg_signal[neg_signal > 0] = np.nan

#plotting
plt.style.use('fivethirtyeight')
plt.plot(pos_signal, color='r')
plt.plot(neg_signal, color='b')
plt.savefig('pos_neg.png', dpi=200)
plt.show()

这篇关于Pyplot - 如果数据小于零,改变线条的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆