简体   繁体   中英

python distplot with color by values

I wany to create a dist plot (preferably using seaborn) with different colors to different range of values. 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.

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. First you need to get equally sized bins (if you want that) such that the plot looks homogenous ( np.histogram ). Afterwards it's just a single numpy filter on your observations and the plot.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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