In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you "how to use python data visualization Seaborn drawing thermal map", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to use python data visualization Seaborn drawing thermal map" this article.
1. Introduction
The idea of a thermal map is simple: replace numbers with colors.
Now, this visualization style has come a long way from the original color-coded table. Thermal maps are widely used in geospatial data. This kind of graph is usually used to describe the density or intensity of variables, pattern visualization, variance and even exception visualization.
Since thermal maps have so many applications, this article will introduce how to use Seaborn to create thermal maps.
two。 Chestnut
First of all, we import the Pandas and Numpy libraries, which can help us with data preprocessing.
Import pandas as pdimport matplotlib.pyplot as pltimport seaborn as sbimport numpy as np
For example, the data set we use is a sample of 80 different cereals, let's take a look at their composition.
An example dataset is shown below:
In the image above, the first behavior header, and then for each row, the first column lists the name of the grain, and the following columns 4 to 16 list the values of the 13 main components contained in each grain.
3. Data preprocessing
After solving the problem, we analyze the correlation between 13 different components of each grain, and we can use the coor () function in the Pandas library to calculate the correlation.
The code is as follows:
# read datasetdf = pd.read_csv ('data/cereal.csv') # get correlationsdf_corr = df.corr () # 13X13print (df_corr)
The results are as follows:
Calories protein fat... Weight cups rating
Calories 1.000000 0.019066 0.498610... 0.696091 0.087200-0.689376
Protein 0.019066 1.000000 0.208431... 0.216158-0.244469 0.470618
Fat 0.498610 0.208431 1.000000... 0.214625-0.175892-0.409284
Sodium 0.300649-0.054674-0.005407... 0.308576 0.119665-0.401295
Fiber-0.293413 0.500330 0.016719... 0.247226-0.513061 0.584160
Carbo 0.250681-0.130864-0.318043... 0.135136 0.363932 0.052055
Sugars 0.562340-0.329142 0.270819... 0.450648-0.032358-0.759675
Potass-0.066609 0.549407 0.193279... 0.416303-0.495195 0.380165
Vitamins 0.265356 0.007335-0.031156... 0.320324 0.128405-0.240544
Shelf 0.097234 0.133865 0.263691... 0.190762-0.335269 0.025159
Weight 0.696091 0.216158 0.214625... 1.000000-0.199583-0.298124
Cups 0.087200-0.244469-0.175892...-0.199583 1.000000-0.203160
Rating-0.689376 0.470618-0.409284...-0.298124-0.203160 1.000000
[13 rows x 13 columns]
Then we remove the last few components that are less relevant, as follows:
# irrelevant fieldsfields = ['rating',' shelf', 'cups',' weight'] # drop rowsdf_corr.drop (fields, inplace=True) # 9X13# drop colsdf_corr.drop (fields, axis=1, inplace=True) # 9X9print (df_corr)
The results are as follows:
We know that the correlation matrix is a symmetric matrix, and the values of the upper triangle and the lower triangle are the same, which brings a lot of repetition.
4. Drawing thermal map
Fortunately, we can use the Mask matrix to generate the heat map in Seaborn, so let's first generate the Mask matrix.
Np.ones_like (df_corr, dtype=np.bool)
The results are as follows:
Then we get the upper triangular matrix. Using the np.triu function in Numpy, we can return the Mask corresponding to the upper triangular matrix.
As follows:
Mask = np.triu (np.ones_like (df_corr, dtype=np.bool))
The results are as follows:
Next, let's draw a thermal map, as follows:
Sb.heatmap (df_corr,mask=mask) plt.show ()
At this time, the running result is as follows:
5. Add Numeric value
Looking at the image above, although we used Mask to generate the heat map, there are still two empty cells in the image (shown in the red circle).
Of course we can filter it as we draw it. That is, filter out the mask and df_corr corresponding to the above circle, respectively.
The code is as follows:
# adjust mask and dfmask = mask [1corr,:-1] corr = df_corr.iloc [1VR,:-1] .copy ()
At the same time, we can set the corresponding parameters of heatmap to display the corresponding values.
The complete code is as follows:
Def test2 (): # read dataset df = pd.read_csv ('data/cereal.csv') # get correlations df_corr = df.corr () # 13X13 # irrelevant fields fields = [' rating', 'shelf',' cups', 'weight'] df_corr.drop (fields, inplace=True) # 9X13 # drop cols df_corr.drop (fields, axis=1, inplace=True) # 9X9 mask = np.triu (np.ones_like (df_corr) Dtype=np.bool) # adjust mask and df mask=mask [1df_corr.iloc,:-1] corr = df_corr.iloc [1df_corr.iloc,-1] .copy () # plot heatmap sb.heatmap (corr, mask=mask, annot=True, fmt= ".2f", cmap='Blues', vmin=-1, vmax=1, cbar_kws= {"shrink": .8}) # yticks plt.yticks (rotation=0) plt.show ()
The running results are as follows:
6. Color palette optimization
Then we continue to optimize the visualization, considering that the correlation coefficient ranges from-1 to 1, so the color changes in two directions. Based on this, palettes diverging from the middle to both sides will have a better visual effect than continuous palettes. An example of a divergent palette is shown below:
In the Seaborn library, there is a function driverging_palette that generates divergent palettes, which is used to build colormaps, using one color on each side and converging into another color in the center.
The full form of this function is as follows:
Diverging_palette (h_neg, h_pos, center= 75, lump 50, sep=1,n=6, center= "light", as_cmap=False)
This function uses color representations of HUSL, namely hue,Saturation and Lightness. Here we check the website to select the color of the palette we set next.
Last but not least, don't forget to set the title on our image and use the title function.
The complete code is as follows:
Def test3 (): # read dataset df = pd.read_csv ('data/cereal.csv') # get correlations df_corr = df.corr () # 13X13 # irrelevant fields fields = [' rating', 'shelf',' cups', 'weight'] df_corr.drop (fields, inplace=True) # 9X13 # drop cols df_corr.drop (fields, axis=1, inplace=True) # 9X9 fig, ax = plt.subplots (figsize= (12) ) # mask mask= np.triu (np.ones_like (df_corr, dtype=np.bool)) # adjust mask and df mask=mask [1dtype=np.bool,-1] corr = df_corr.iloc [1dtype=np.bool,:-1] .copy () # color map cmap= sb.diverging_palette (0,230,90,60, as_cmap=True) # plot heatmap sb.heatmap (corr, mask=mask, annot=True, fmt= ".2f", linewidths=5, cmap=cmap Vmin=-1, vmax=1, cbar_kws= {"shrink": .8}, square=True) # ticks yticks = [i.upper () for i in corr.index] xticks = [i.upper () for i in corr.columns] plt.yticks (plt.yticks () [0], labels=yticks, rotation=0) plt.xticks (plt.xticks () [0], labels=xticks) # title title = 'CORRELATION MATRIX\ nSAMPLED CEREALS COMPOSITION\ n' plt.title (title, loc='left' Fontsize=18) plt.show ()
The running results are as follows:
Doesn't it look a lot taller? Sure enough, human beings are visual animals.
The above is all the contents of the article "how to use python data to visualize Seaborn thermal map". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.