2016-04-06 2 views
5

У меня проблема с функцией conturf matplotlib. У меня есть файл данных txt, из которого я импортирую свои данные. У меня есть столбцы данных (pm1 и pm2), и я выполняю 2D-гистограмму. Я хочу построить эти данные как трехмерную гистограмму и как график контура, чтобы увидеть, где расположены максимальные значения.3D-гистограммы и контурные графики Python

Это мой код:

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 я получаю ошибку: Length of x must be number of columns in z и если I place dz Я получаю Input z must be a 2D array Я также пробовал использовать xedges и yexges, но это не решает проблему.

Я думаю, что проблема связана с формой возврата функции histogram2D. Но я не знаю, как это решить.

Я также хотел бы выполнить 3D-график с изменением цветового кода с минимальным до максимального значения. Есть ли способ сделать это?

Спасибо

ответ

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.

+0

Ссылки на строки настройки цвета: [pylab example] (http://matplotlib.org/examples/pylab_examples/hist_colormapped.html) и [это сообщение] (http://stackoverflow.com/questions/11950375/apply -Цвет-карта к MPL-инструментарию-mplot3d-axes3d-bar3d) – lanery

Смежные вопросы