Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用渐变色为分布图的条形图着色?_Python_Python 2.7_Pandas_Matplotlib_Seaborn - Fatal编程技术网

Python 如何使用渐变色为分布图的条形图着色?

Python 如何使用渐变色为分布图的条形图着色?,python,python-2.7,pandas,matplotlib,seaborn,Python,Python 2.7,Pandas,Matplotlib,Seaborn,我有以下数据帧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\u diff'],hist=“true” 我想用渐变来给这些条上色:较暗的颜色应该被赋予较高概率的值 我试图这样做,但没有成功: norm = plt.Normalize(df

我有以下数据帧
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\u 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))
的话,我就无法调整这个图的大小。它总是很小。我还需要保持我的箱子的大小
25
。在我的代码中,我使用
plt.xticks(np.arange(min(df_day_route_veh_counts['time_diff')),max(df_day_route_veh_counts['time_diff'))+100,25.0))
。如何使这种方法适合您的代码?
plt.subplot(figsize=(14,8))
设置图形大小。
plt.xticks
不设置箱子大小。它设置刻度在轴上的位置。但它也适用于此代码。如果要更改柱状图的箱子大小,需要使用
np.histogram
bins
参数。我应该手动创建这些箱子吗?我不能y每个箱子应等于0.1?例如,
sns.distplot(df['time_diff')、hist=“true”
plt.xticks
的组合根据
plt.xticks
定义的距离自动创建箱子。您可以指定箱子数量或箱子边缘。后一种情况显示在更新的答案中。