2017-08-05 75 views
1

我有以下數據框df如何使用漸變顏色爲配色圖上的顏色條?

time_diff avg_trips_per_day 
0.450000 1.0 
0.483333 1.0 
0.500000 1.0 
0.516667 2.0 
0.533333 5.0 

然後我創建了一個分佈圖如下ax = sns.distplot(df['time_diff'],hist="true"

我想使用漸變對條進行着色:應將較暗的顏色分配給較高概率的值。

我試圖做這種方式,但它沒有工作:

norm = plt.Normalize(df["time_diff"].values.min(), df["time_diff"].values.max()) 
colors = plt.cm.YlGnBu(norm(df_imh_unique["time_diff"])) 
ax = sns.distplot(df['time_diff'],hist="true", color=colors) 

回答

1

在你的代碼試圖根據數據值本身上色酒吧。但是,直方圖顯示倉內數值的頻率。因此,您需要使用頻率來確定條形的顏色。

當分離直方圖和繪圖時,這更容易理解。

import numpy as np 
import matplotlib.pyplot as plt 

data = np.random.rayleigh(size=30) 

hist, edges = np.histogram(data) 

norm = plt.Normalize(hist.min(), hist.max()) 
colors = plt.cm.YlGnBu(norm(hist)) 

fig, ax = plt.subplots() 
ax.bar(edges[:-1], hist, np.diff(edges), color=colors, ec="k", align="edge") 

plt.show() 

enter image description here

您可以在通話設置垃圾箱,以np.histogram,例如0.1大容器,你會使用

bins = np.arange(0, data.max()+0.1, 0.1) 
hist, edges = np.histogram(data, bins=bins) 

由於seaborn distplot結合直方圖化和繪圖的兩個步驟,設置欄的顏色只可能創建的情節。這當然不是最佳的,但對於完整性,它使用現有的distplot的解決方案可能是這樣的:

import numpy as np 
import matplotlib.pyplot as plt 
import seaborn as sns 

data = np.random.rayleigh(size=30) 

ax = sns.distplot(data) 

vals = np.array([rec.get_height() for rec in ax.patches]) 
norm = plt.Normalize(vals.min(), vals.max()) 
colors = plt.cm.YlGnBu(norm(vals)) 

for rec, col in zip(ax.patches, colors): 
    rec.set_color(col) 

plt.show() 

enter image description here

+0

感謝。如果我在開始時使用'plt.figure(figsize =(14,8))',我無法調整此圖。它總是很小。 – Dinosaurius

+0

另外我需要保持我的大小爲'25'的箱子。在我的代碼中,我使用'plt.xticks(np.arange(min(df_day_route_veh_counts ['time_diff']),max(df_day_route_veh_counts ['time_diff'])+ 100,25.0))''。我如何將這種方法適用於您的代碼? – Dinosaurius

+0

'plt.subplots(figsize =(14,8))'設置數字大小。 'plt.xticks'不設置bin大小。它在軸上設置刻度的位置。但它也可以在這個代碼中工作。如果要更改直方圖的bin大小,則需要使用'np.histogram'的'bins'參數。 – ImportanceOfBeingErnest