如何使用渐变颜色为配色图上的颜色条?
问题描述:
我有以下数据框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)
答
在你的代码试图根据数据值本身上色酒吧。但是,直方图显示仓内数值的频率。因此,您需要使用频率来确定条形的颜色。
当分离直方图和绘图时,这更容易理解。
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()
您可以在通话设置垃圾箱,以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()
感谢。如果我在开始时使用'plt.figure(figsize =(14,8))',我无法调整此图。它总是很小。 – Dinosaurius
另外我需要保持我的大小为'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
'plt.subplots(figsize =(14,8))'设置数字大小。 'plt.xticks'不设置bin大小。它在轴上设置刻度的位置。但它也可以在这个代码中工作。如果要更改直方图的bin大小,则需要使用'np.histogram'的'bins'参数。 – ImportanceOfBeingErnest