创建条件图python [英] Create a conditional plot python

查看:33
本文介绍了创建条件图python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想绘制小于或等于某个数字(假设为 15)的值.我可以在数据框的一列中找到这些值,如果这些值不小于或等于15,则我不想绘制它们.

I want to plot just values which are less or equal a certain number (let's say 15). I can find these values in one column of my dataframe and if these values aren't less or equal 15, I don't want to plot them.

您能帮我找到解决方法吗?

Can you help me find a solution?

推荐答案

0.生成一个最小的示例
(通常应由提出问题的人采取此步骤;这是您的问题如此频繁被否决的原因之一)

0. Produce a minimal example
(This step should normally be taken by the one who asks the question; which is one of the reasons your question was downvoted so often)

import numpy as np; np.random.seed(4)
import matplotlib.pyplot as plt
import pandas as pd
plt.rcParams["figure.figsize"] = 5,3

x = np.linspace(2.1,6.3,num=70)
y = np.cumsum(np.random.normal(size=len(x))*10.)
df = pd.DataFrame({"x":x, "y":y})

plt.plot(df.x,df.y)

plt.show()

现在您有几种选择:

1.限制视图

您可以简单地限制图的视图,以使其y比例最大不超过15.这是通过

You can simply limit the view of the plot such that its y scale only goes up to 15. This is done via

plt.ylim(-30,15)

2.过滤数据框

您可以按条件过滤数据框.这意味着在结果数据框中,只有条件为肉的那些行存在.

You can filter the dataframe by a condition. This means that in the resulting dataframe only those rows where the condition is meat are present.

df2 = df[df.y <= 15]

plt.plot(df.x,df.y, label="original")
plt.plot(df2.x,df2.y, label="filtered to y <= 15")

可以看出,大于 15 的值不在过滤曲线中.但是,新曲线看起来像是连续的,根据所需的图形可能会令人困惑.

As can be seen, the values above 15 are not in the filtered curve. However, it also looks like the new curve beeing continuous, which may be confusing depending on what graph is desired.

3.将 15 以上的所有值设置为 nan

数据集中nan(不是数字)的值不会被绘制.通过将所有大于15的值设置为nan可以使用它.

Values in a dataset which are nan (not a number) are not plotted. This can be used, by setting all values above 15 to nan.

df2 = df.copy()
df2[df2.y > 15] = np.nan

plt.plot(df2.x,df2.y, label="y > 15 set to nan")

附录:使用两种不同的条件
通过将它们与& (和")或 | (或")之类的逻辑运算符组合在一起,可以使用多个条件.因此,将所有大于15或小于-15的值都设置为nan

Appendix: Using two different conditions
You can use several conditions by combining them with logical operators like & ("and") or | ("or"). So setting all values which are either above 15 or below -15 to nan, you'd do

df2[(df2.y > 15) | (df2.y < -15)] = np.nan

这篇关于创建条件图python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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