3D直方图和轮廓图Python

时间:2016-04-06 18:17:30

标签: python matplotlib histogram contour histogram2d

我的matplotlib的contourf函数有问题。我有一个txt数据文件,我从中导入我的数据。我有数据列(pm1和pm2),我正在执行2D直方图。我想将这些数据绘制为3D直方图和等高线图,以查看最大值的位置。

这是我的代码:

text-indent: -999px;

我可以绘制三维条形图,但我无法绘制轮廓一,如果我将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() 放在contourf函数中,我会得到错误:hist如果我放置{{1}我得到Length of x must be number of columns in z 我也尝试过使用xedges和yexges,但这并没有解决问题。

我认为这个问题与函数histogram2D的返回形状有关。但我不知道如何解决它。

我还想执行3D条形图,其中颜色代码从最小值变为最大值。无论如何要做到这一点?

谢谢

1 个答案:

答案 0 :(得分:1)

也许我不明白你到底想要做什么,因为我不知道你的数据是什么样子,但让你的contourf情节共享同一个轴似乎是错误的你的bar3d情节。如果您将没有3D投影的轴添加到新图形,您应该可以使用contourf制作hist图。使用来自随机正态分布的数据的示例:

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

相关问题