以下代码:
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()
产生如下图:
如何将主题从红色更改为蓝色?像这样:
import seaborn as sns
sns.palplot(sns.color_palette("Blues"))
答案 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_)