在Matplotlib中为密度图指定颜色范围

时间:2018-12-26 18:36:44

标签: python matplotlib

以下代码:

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde

# Generate fake data
x = np.random.normal(size=1000)
y = x * 3 + np.random.normal(size=1000)

# Calculate the point density
xy = np.vstack([x,y])
z = gaussian_kde(xy)(xy)

# Sort the points by density, so that the densest points are plotted last
idx = z.argsort()
x, y, z = x[idx], y[idx], z[idx]

fig, ax = plt.subplots()
ax.scatter(x, y, c=z, s=50, edgecolor='')
plt.show()

产生如下图:

enter image description here

如何将主题从红色更改为蓝色?像这样:

import seaborn as sns
sns.palplot(sns.color_palette("Blues"))

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以按以下方式将任何颜色图分配给scatter图。 Here将在matplotlib中找到所有现有的颜色图。

所需的颜色图被命名为Blues。您必须导入matplotlib.cm才能访问颜色图,然后在散点图中将所需的颜色图作为参数传递给cmap。此外,您可以显示颜色条以解释颜色。如果要反转颜色图,只需在该颜色图的末尾添加_r。例如,Blues_r将使地图反转,其比例现在从蓝色(低)变为白色(高)。

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
import matplotlib.cm as cm

# Generate fake data
x = np.random.normal(size=1000)
y = x * 3 + np.random.normal(size=1000)

# Calculate the point density
xy = np.vstack([x,y])
z = gaussian_kde(xy)(xy)

# Sort the points by density, so that the densest points are plotted last
idx = z.argsort()
x, y, z = x[idx], y[idx], z[idx]

fig, ax = plt.subplots()
ax_ = ax.scatter(x, y, c=z, cmap=cm.Blues, s=50, edgecolor='')
plt.colorbar(ax_)

enter image description here