在matplotlib中使用3D数据进行热图

时间:2014-02-24 04:11:04

标签: python matplotlib 3d

我想用我的3D数据生成热图。

我已经能够使用这些数据绘制trisurf。

有人可以帮我生成热图吗?我看过在线教程,但它们看起来都非常复杂。我在这个网站上发现了一个在matplotlib中生成具有散点的热图,但是它只有2D数据。

生成trisurf的代码是

from mpl_toolkits.mplot3d import Axes3D

from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np

n_angles = 36
n_radii = 8

# An array of radii
# Does not include radius r=0, this is to eliminate duplicate points
radii = np.linspace(0.125, 1.0, n_radii)

# An array of angles
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)

# Repeat all angles for each radius
angles = np.repeat(angles[...,np.newaxis], n_radii, axis=1)

# Convert polar (radii, angles) coords to cartesian (x, y) coords
# (0, 0) is added here. There are no duplicate points in the (x, y) plane

x,y,z =np.loadtxt('output/flash_KR_endowment_duration_3D.dat',delimiter='\t',usecols=(0,1,2),unpack=True)
#x,y,z =np.loadtxt('output/disk_KR_endowment_duration_3D.dat',delimiter='\t',usecols=(0,1,2),unpack=True)


fig = plt.figure()
ax = fig.gca(projection='3d')
#fig.suptitle(suptitle, fontsize=12, fontweight='bold')


#ax.set_title("Disk Kryder's Rate-Endowment-Duration Plot",fontsize=12)
ax.set_title("Flash Kryder's Rate-Endowment-Duration Plot",fontsize=12)

ax.set_xlabel("Kryder's rate")
ax.set_ylabel("Duration")
ax.set_zlabel("Endowment")


surf = ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.2)
fig.colorbar(surf, shrink=.7, aspect=20)

plt.show()

数据是3列。说X,Y,Z。我尝试过使用颜色的3D散点图。但我正在寻找热图。

1 个答案:

答案 0 :(得分:0)

如果您只是“想要使用第三维进行着色”,您可以这样做:

import pandas as pd
import numpy as np
import plotly.plotly as plotly
from plotly.graph_objs import Data, Heatmap

plotly.sign_in("username", "api_key") # this is annoying but you can get one after registering - free

# generate tridimentional data
pp = pd.Panel(np.random.rand(20, 20, 20))

# crunch (sum, average...) data along one axis
crunch = pp.sum(axis=0)

# now plot with plot.ly or matplotlib as you wish
data = Data([Heatmap(z=np.array(crunch))])
plotly.image.save_as(data, "filename.pdf")

结果 - 将第三个3D数据变量的热图作为颜色: Heatmap with 3rd variable of 3D data as colour 此外,您可以使用循环绘制每个轴组合:

## Plot
# for each axis, sum data along axis, plot heatmap
# dict is axis:[x,y,z], where z is a count of that variable
desc = {0 : ["ax1", "ax2", "ax3"], 1 : ["ax1", "ax2", "ax3"], 2 : ["ax1", "ax2", "ax3"]}
for axis in xrange(3):
    # crunch (sum) data along one axis
    crunch = pp.sum(axis=axis)

    # now let's plot
    data = Data([Heatmap(
        z=np.array(crunch),
        x=crunch.columns,
        y=crunch.index)]
    )
    plotly.image.save_as(data,
        "heatmap_{0}_vs_{1}_count_of_{2}".format(desc[axis][0], desc[axis][1], desc[axis][2])
    )