Python:如何创建二维密度图/热图

时间:2020-03-10 22:44:01

标签: python matplotlib plot colorbar

我正在用python编码。 我有3个数组x,y和z,我想用色条绘制平面图(x,y)中z值的二维密度图。

所以在我的图中,点x [0]和y [0]的颜色将由z [0]的值确定,点x [1]和y [1]的颜色将是由z [1]等的值确定。

有人知道怎么做吗?

谢谢

3 个答案:

答案 0 :(得分:1)

签出https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html

对于不同的颜色图:https://matplotlib.org/tutorials/colors/colormaps.html

您需要的示例代码将是这样

 #--------------------------Plotting starts here---------------------------------#

    fig, ax0 = plt.subplots()

    im0 = plt.scatter(x,y,s=1,c=z, cmap='bwr')


#------------------if you want to use pcolormesh-------------------
#----------and have Z values stored as a numpy array Data---------------------#

    #X,Y = np.meshgrid(x,y)
    #im0 = ax0.pcolormesh(X,Y,Data, cmap="YourFavouriteColormap')

    cbar = fig.colorbar(im0,ax=ax0)
    ax0.set_title("Your title")
    plt.xlabel("xlabel")
    plt.ylabel("ylabel")
    filename = "prefix" + "."+ "fileformat"
    plt.savefig(filename)

编辑1: 根据您的评论之一,如果您有网格数据,则可以尝试pcolormesh并尝试着色(插值的可选参数)。

 shading{'flat', 'gouraud'}, optional

    The fill style, Possible values:

        'flat': A solid color is used for each quad. The color of the quad (i, j), (i+1, j), (i, j+1), (i+1, j+1) is given by C[i, j].
        'gouraud': Each quad will be Gouraud shaded: The color of the corners (i', j') are given by C[i',j']. The color values of the area in between is interpolated from the corner values. When Gouraud shading is used, edgecolors is ignored.

答案 1 :(得分:0)

您可以将matplotlib的散点图与图例和网格一起使用,其中每个圆的大小可以参考z值。这是我从here获得的示例:

volume = np.random.rayleigh(27, size=40)
amount = np.random.poisson(10, size=40)
ranking = np.random.normal(size=40)
price = np.random.uniform(1, 10, size=40)

fig, ax = plt.subplots()

scatter = ax.scatter(volume, amount, c=ranking, s=0.3*(price*3)**2,
                     vmin=-3, vmax=3, cmap="Spectral")

legend1 = ax.legend(*scatter.legend_elements(num=5),
                    loc="upper left", title="Ranking")
ax.add_artist(legend1)

kw = dict(prop="sizes", num=5, color=scatter.cmap(0.7), fmt="$ {x:.2f}",
          func=lambda s: np.sqrt(s/.3)/3)
legend2 = ax.legend(*scatter.legend_elements(**kw),
                    loc="lower right", title="Price")

plt.show()

输出:

enter image description here

答案 2 :(得分:0)

针对您的评论Ashli​​nJP: 无论哪种方式,我仍然会收到错误消息:“ imshow()为关键字参数'cmap'获得了多个值”

我不知道它是否重要,但是我使用python 2.7

实际上我的代码是:

import numpy as np
import matplotlib.pyplot as plt


x,y,z = np.loadtxt('gamma.txt', unpack = True)
fig, ax0 = plt.subplots()

cmap = plt.get_cmap('viridis') 
im0 = ax0.imshow(x,y,z, cmap=cmap, interpolation="gaussian")

cbar = fig.colorbar(im0,ax=ax0)


ax0.set_title("Your title")
plt.xlabel("xlabel")
plt.ylabel("ylabel")