首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >3D直方图和等高线图Python

问3D直方图和等高线图Python
EN

Stack Overflow用户
提问于 2016-04-06 18:17:30
回答 1查看 1.7K关注 0票数 5

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

这是我的密码:

代码语言:javascript
复制
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放在等高线函数中,我会得到一个错误:Length of x must be number of columns in z,如果我放置dz,我得到Input z must be a 2D array,我也尝试过使用x边和yexges,但这并不能解决问题。

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

我还想要执行一个三维条形图的颜色代码从最小到最大值。有什么事要做吗?

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-07 07:12:03

也许我不明白您到底想做什么,因为我不知道您的数据是什么样子的,但是让您的contourf图与您的bar3d图共享相同的轴似乎是错误的。如果您将一个没有三维投影的轴添加到一个新的图形中,那么您应该能够使用contourf很好地制作一个hist图。使用随机正态分布数据的示例:

代码语言:javascript
复制
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()

返回类似于这的图像。

至于你的第二个问题,关于一个彩色编码的3D条形图,这个怎么样(使用与上面相同的数据,但大小为1/10 ):

代码语言:javascript
复制
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()

我得到了这幅图像。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36459220

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档