Kil*_*.G. 5 python matplotlib histogram contour histogram2d
我的matplotlib的contourf函数有问题.我有一个txt数据文件,我从中导入我的数据.我有数据列(pm1和pm2),我正在执行2D直方图.我想将此数据绘制为3D直方图和等高线图,以查看最大值的位置.
这是我的代码:
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()
Run Code Online (Sandbox Code Playgroud)
我可以绘制3D条形图,但我不能绘制轮廓之一,如果我把hist在contourf功能我得到的错误: Length of x must be number of columns in z如果我把dz我弄Input z must be a 2D array
我也可以选择使用xedges和yexges尝试,但这并没有解决问题.
我认为这个问题与函数histogram2D的返回形状有关.但我不知道如何解决它.
我还想执行一个3D条形图,其中颜色代码从最小值变为最大值.无论如何要做到这一点?
谢谢
也许我不明白你到底想做什么,因为我不知道你的数据是什么样的,但让你的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()
Run Code Online (Sandbox Code Playgroud)
返回这样的图像。
至于你的第二个问题,关于颜色编码的 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()
Run Code Online (Sandbox Code Playgroud)
我明白了这个形象。
| 归档时间: |
|
| 查看次数: |
1184 次 |
| 最近记录: |