简体   繁体   中英

How to plot a heat map with different sizes of rectangles in python

I have a dataframe looks like below:

import pandas as pd

df = pd.DataFrame({'id':[1,2,3,4], 'grade':[98,50,10,100], 'c':[1000,29,69,150]})

I want to plot a heatmap with sub-rectangles that their sizes represent the values from column 'c' and the colors represent the values from 'grade'

If it is too complicated then I can just go with colors and grade pair and not the size and "c"

I did some researches and found some examples with using sns.heatmap, but I could not get that work.

You don't need heatmap, you need treemap .
Based on this link , you can use squarify like this:

import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import squarify # pip install squarify (algorithm for treemap)</pre>
import pandas as pd

df = pd.DataFrame({'id':[1,2,3,4], 'grade':[98,50,10,100], 'c':[1000,29,69,150]})

# Create a dataset:
my_values=df.c # YOUR VALUES
 
# create a color palette, mapped to these values
cmap = matplotlib.cm.Blues
mini=min(my_values)
maxi=max(my_values)
norm = matplotlib.colors.Normalize(vmin=mini, vmax=maxi)
colors = [cmap(norm(value)) for value in my_values]
 
# Change color
squarify.plot(sizes=my_values, alpha=.8, color=colors )
plt.axis('off')
plt.show()

树形图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM