简体   繁体   English

python distplot颜色按值

[英]python distplot with color by values

I wany to create a dist plot (preferably using seaborn) with different colors to different range of values. 我渴望创建一个具有不同颜色到不同值范围的dist图(最好使用seaborn)。 I have the vector: 我有矢量:

[3,1,2,3,5,6,8,0,0,5,7,0,1, 0.2]

And I want to create a distplot such that all the parts with range 0 to 1 will be red and all the other will be blue. 我想创建一个distplot,使所有范围从0到1的部分将变为红色,而所有其他部分将变为蓝色。

What is the best way to do so? 最好的方法是什么?

I don't know if there is an easy way in seaborn to do this but doing the plot yourself is probably much easier. 我不知道seaborn中是否有简单的方法可以做到这一点,但是自己进行绘制可能要容易得多。 First you need to get equally sized bins (if you want that) such that the plot looks homogenous ( np.histogram ). 首先,您需要获取大小相等的垃圾箱(如果需要),以使图看起来均匀( np.histogram )。 Afterwards it's just a single numpy filter on your observations and the plot. 然后,它只是您的观察结果和图上的单个numpy过滤器。

import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
x = np.array([3,1,2,3,5,6,8,0,0,5,7,0,1, 0.2])
# make equal binning through the range, you can adapt the bin size here
counts, bins = np.histogram(x, bins=10)

# here we do the filtering and split the observations based on your color code
x1 = x[(x <= 1) & (x >= 0)]
x2 = x[~((x <= 1) & (x >= 0))]

# finally, do the plot
f, ax = plt.subplots()
ax.hist(x1, bins=bins, color="tab:red")
ax.hist(x2, bins=bins, color="tab:blue")
ax.set(xlabel="Measurement", ylabel="Counts", title="histogram with 2 colors")
sns.despine()

Gives you: 给你:

在此处输入图片说明

I think you need a scatter plot. 我认为您需要一个散点图。 In that case, you can try the following solution. 在这种情况下,您可以尝试以下解决方案。 Here you first create a column of colors based on your condition and then assign those colors to the scatter plot. 在这里,您首先根据条件创建一列颜色,然后将这些颜色分配给散点图。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

data = np.array([3, 1, 2, 3, 5, 6, 8, 0, 0, 5, 7, 0,1, 0.2])
df = pd.DataFrame({'data':data}).reset_index()

df['colors'] = np.where(data<1, 'red', 'blue')
plt.scatter(df['index'], df['data'], c=df['colors'])

在此处输入图片说明

Alternative would be to plot directly using DataFrame 替代方法是直接使用DataFrame进行绘制

data = np.array([3, 1, 2, 3, 5, 6, 8, 0, 0, 5, 7, 0,1, 0.2])
df = pd.DataFrame({'data':data}).reset_index()

colors = np.where(data<1, 'red', 'blue')
df.plot(kind='scatter', x='index', y='data',c=colors)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM