[英]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.