Heatmap with circles indicating size of population

后端 未结 3 416
长发绾君心
长发绾君心 2020-12-06 15:00

Hi I would like to produce a heatmap in Python, similar to the one shown, where the size of the circle indicates the size of the sample in that cell. I looked in seaborn\'s

3条回答
  •  無奈伤痛
    2020-12-06 15:24

    One option is to use matplotlib's scatter plots with legends and grid. You can specify size of those circles with specifying the scales. You can also change the color of each circle. You should somehow specify X,Y values so that the circles sit straight on lines. This is an example I got from 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()
    
    # Because the price is much too small when being provided as size for ``s``,
    # we normalize it to some useful point sizes, s=0.3*(price*3)**2
    scatter = ax.scatter(volume, amount, c=ranking, s=0.3*(price*3)**2,
                         vmin=-3, vmax=3, cmap="Spectral")
    
    # Produce a legend for the ranking (colors). Even though there are 40 different
    # rankings, we only want to show 5 of them in the legend.
    legend1 = ax.legend(*scatter.legend_elements(num=5),
                        loc="upper left", title="Ranking")
    ax.add_artist(legend1)
    
    # Produce a legend for the price (sizes). Because we want to show the prices
    # in dollars, we use the *func* argument to supply the inverse of the function
    # used to calculate the sizes from above. The *fmt* ensures to show the price
    # in dollars. Note how we target at 5 elements here, but obtain only 4 in the
    # created legend due to the automatic round prices that are chosen for us.
    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()
    

    Output:

提交回复
热议问题