2021年3月1日 星期一

[ Python 常見問題 ] Seaborn - create a heatmap of two categorical variables

 Source From Here

Question
I have the following datasets of three variables:
  1. df['Score'] Float dummy (1 or 0)  
  2. df['Province'] an object column where each row is a region  
  3. df['Product type'] an object indicating the industry.  
I would like to create a jointplot where on the x axis I have the different industries, on the y axis the different provinces and as colours of my jointplot I have the relative frequency of the score. Something like this. https://seaborn.pydata.org/examples/hexbin_marginals.html

HowTo
If you are looking for a heatmap, you could use Seaborn heatmap function. However, you need to pivot your table first.

Just creating a small example:
  1. import numpy as np   
  2. import pandas as pd  
  3. import seaborn as sns  
  4. import matplotlib.pyplot as plt  
  5.   
  6. score = [11101000]  
  7. provinces = ['Place1' ,'Place2' ,'Place2''Place3','Place1''Place2','Place3','Place1']  
  8. products = ['Product1' ,'Product3' ,'Product2''Product2','Product1''Product2','Product1','Product1']  
  9. df = pd.DataFrame({'Province': provinces,  
  10.                    'Product type': products,  
  11.                    'score': score  
  12.                   })  
My df looks like:
  1.    'Province''Product type''score'  
  2. 0   Place1    Product1      1  
  3. 1   Place2    Product3      1  
  4. 2   Place2    Product2      1  
  5. 3   Place3    Product2      0  
  6. 4   Place1    Product1      1  
  7. 5   Place2    Product2      0  
  8. 6   Place3    Product1      0  
  9. 7   Place1    Product1      0  
Then:
  1. df_heatmap = df.pivot_table(values='score',index='Province',columns='Product type',aggfunc=np.mean)  
  2. sns.heatmap(df_heatmap,annot=True)  
  3. plt.show()  
The result is:


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...