3D直方图和轮廓图Python

5
我在使用matplotlib的contourf函数时遇到了问题。我有一个文本数据文件,从中导入我的数据。我的数据有两列(pm1和pm2),我正在进行二维直方图分析。我想将这些数据绘制成三维直方图和等高线图,以查看最大值所在位置。
以下是我的代码:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
rows = np.arange(200,1300,10)

hist, xedges, yedges = np.histogram2d (pm1_n, pm2_n, bins = (rows, rows) )
elements = (len(xedges) - 1) * (len(yedges) - 1)


xpos, ypos = np.meshgrid(xedges[:-1], yedges[:-1])

xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(elements)
dx = 0.1 * np.ones_like(zpos)
dy = dx.copy()
dz = hist.flatten()

#####The problem is here#####

#ax.contourf(xpos,ypos,hist)
#ax.bar3d(xpos, ypos, zpos, dx, dy, dz, zsort='average')

plt.show()

我可以绘制3D条形图,但无法绘制轮廓线图。如果我将hist放在contourf函数中,会出现错误:x的长度必须是z中的列数。如果我放置dz,则会出现输入z必须是2D数组的错误。
我也尝试使用xedges和yexges,但这并没有解决问题。
我认为问题与histogram2D函数返回值的形状有关。但我不知道如何解决它。
我还想执行一个3D条形图,并且希望颜色代码从最小值到最大值进行变化。有没有任何方法可以实现这个功能?
谢谢。
1个回答

1
也许我不理解你的具体操作,因为我不知道你的数据长什么样,但是似乎在同一个轴上同时使用contourf图和bar3d图是错误的。如果你在新的图中添加一个没有3D投影的轴,你应该可以使用hist来制作一个contourf图。以下是使用随机正态分布数据的示例:
import numpy as np
import matplotlib.pyplot as plt

n_points = 1000
x = np.random.normal(0, 2, n_points)
y = np.random.normal(0, 2, n_points)

hist, xedges, yedges = np.histogram2d(x, y, bins=np.sqrt(n_points))

fig2D = plt.figure()
ax2D = fig2D.add_subplot(111)
ax2D.contourf(hist, interpolation='nearest', 
              extent=(xedges[0], xedges[-1], yedges[0], yedges[-1]))
plt.show()

返回一个像this的图片。

至于你的第二个问题,关于彩色编码的3D条形图,可以试试这个(使用与上面相同的数据,但大小缩小了1/10):

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.colors as colors

n_points = 100
x = np.random.normal(0, 2, n_points)
y = np.random.normal(0, 2, n_points)

hist, xedges, yedges = np.histogram2d(x, y, bins=np.sqrt(n_points))

# Following your data reduction process
xpos, ypos = np.meshgrid(xedges[:-1], yedges[:-1])

length, width = 0.4, 0.4
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(n_points)
dx = np.ones(n_points) * length
dy = np.ones(n_points) * width
dz = hist.flatten()

# This is where the colorbar customization comes in
dz_normed = dz / dz.max()
normed_cbar = colors.Normalize(dz_normed.min(), dz_normed.max())
# Using jet, but should work with any colorbar
color = cm.jet(normed_cbar(dz_normed))

fig3D = plt.figure()
ax3D = fig3D.add_subplot(111, projection='3d')
ax3D.bar3d(xpos, ypos, zpos, dx, dy, dz, color=color)
plt.show()

我得到了这个图片:this image

对于colorbar的自定义,可以参考以下链接:pylab examplethis post - lanery

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接