在Python中使用mpl_toolkits.axes_grid1绘制密度图
发布时间:2023-12-25 06:18:10
在Python中,我们可以使用mpl_toolkits.axes_grid1库来绘制密度图。密度图可以有效地展示数据的分布情况,特别适用于连续变量的可视化。下面是一个使用例子,具体步骤如下:
1. 导入相关的库和模块:
import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import numpy as np
2. 创建一个二维数组用于生成数据:
x = np.random.randn(1000) y = np.random.randn(1000)
3. 创建一个绘图对象和一个子图对象:
fig, ax = plt.subplots()
4. 创建密度图并添加颜色渐变:
heatmap, xedges, yedges = np.histogram2d(x, y, bins=100) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] im = ax.imshow(heatmap.T, extent=extent, origin='lower', aspect='auto', cmap='hot')
5. 添加颜色条:
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(im, cax=cax)
6. 添加X轴和Y轴标签:
ax.set_xlabel('X')
ax.set_ylabel('Y')
7. 添加标题:
ax.set_title('Density Plot')
8. 显示图形:
plt.show()
完整的代码如下所示:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
x = np.random.randn(1000)
y = np.random.randn(1000)
fig, ax = plt.subplots()
heatmap, xedges, yedges = np.histogram2d(x, y, bins=100)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
im = ax.imshow(heatmap.T, extent=extent, origin='lower', aspect='auto', cmap='hot')
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(im, cax=cax)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_title('Density Plot')
plt.show()
运行上述代码,将生成一个带有颜色渐变的密度图,显示了x和y的数据分布情况。
