本文的数据来自UCI的数据集”sonar”,用pandas直接读取数据。如下:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
% matplotlib inline
target_url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/undocumented/connectionist-bench/sonar/sonar.all-data'
df = pd.read_csv(target_url, header=None, prefix='V')
corr = df.corr()
首先来看看没有进行个性化设置时的显示情况,如下:
f, ax= plt.subplots(figsize = (14, 10))
sns.heatmap(corr,cmap='RdBu', linewidths = 0.05, ax = ax)
ax.set_title('Correlation between features')
f.savefig('sns_style_origin.jpg', dpi=100, bbox_inches='tight')
图片显示效果如下:
seaborn制图的默认效果其实还是不错的。
3 进行个性化设置
对于上面这张图,可能让y轴从下到上,从v0开始显示,这样显示出来的对角线可能更符合我们的视觉显示效果。
这就要用到 将y轴内容进行可逆显示,涉及的代码如下:
ax.invert_yaxis()
其他的个性化设置的代码,包括:
将x轴刻度放置在top位置的几种方法
ax.xaxis.tick_top()
设置坐标轴刻度参数,”axis”不写的时候,默认是x轴和y轴的参数同时调整。
ax.tick_params(axis='y',labelsize=8)
旋转轴刻度上文字方向的两种方法
ax.set_xticklabels(ax.get_xticklabels(), rotation=-90)
保存图片,设置bbox_inches=’tight’,保存的图片则不会出现部分内容显示不全的现象。
f.savefig('sns_style_update.jpg', dpi=100, bbox_inches='tight')
整合好的代码如下,大家可以运行试试效果。
f, ax = plt.subplots(figsize = (14, 10))
cmap = sns.cubehelix_palette(start = 1, rot = 3, gamma=0.8, as_cmap = True)
sns.heatmap(corr,cmap='RdBu', linewidths = 0.05, ax = ax)
ax.set_title('Correlation between features', fontsize=18, position=(0.5,1.05))
ax.invert_yaxis()
ax.set_xlabel('X Label',fontsize=10)
ax.set_ylabel('Y Label',fontsize=15, color='r')
ax.tick_params(axis='y',labelsize=8)
ax.xaxis.tick_top()
ax.set_xticklabels(ax.get_xticklabels(), rotation=-90)
f.savefig('sns_style_update.jpg', dpi=100, bbox_inches='tight')
图形显示效果如下:
这些个性化的设置,其实大部分都是使用的matplotlib的内容,seaborn是基于matplotlib衍生的,所以可以跟matplotlib进行融合使用。
当然,并不是每次都需要进行个性定制,具体可以根据自己的需求来设置。
如果您喜欢我的文章,欢迎关注微信公众号“Python数据之道”(ID:PyDataRoad)