繁体   English   中英

python distplot颜色按值

[英]python distplot with color by values

我渴望创建一个具有不同颜色到不同值范围的dist图(最好使用seaborn)。 我有矢量:

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

我想创建一个distplot,使所有范围从0到1的部分将变为红色,而所有其他部分将变为蓝色。

最好的方法是什么?

我不知道seaborn中是否有简单的方法可以做到这一点,但是自己进行绘制可能要容易得多。 首先,您需要获取大小相等的垃圾箱(如果需要),以使图看起来均匀( np.histogram )。 然后,它只是您的观察结果和图上的单个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()

给你:

在此处输入图片说明

我认为您需要一个散点图。 在这种情况下,您可以尝试以下解决方案。 在这里,您首先根据条件创建一列颜色,然后将这些颜色分配给散点图。

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'])

在此处输入图片说明

替代方法是直接使用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