seaborn简介
Seaborn是python中的一个可视化库,对matplotlib的封装,与plotly类似,能更方便的做出易调整、美观的图表。能够显示更多信息。同时官网提供了多种示例图库,方便进行实践练习。
官网地址:
seaborn: statistical data visualizationhttps://seaborn.pydata.org/
自定义数据绘制示例
# 导入数据可视化所需要的库
df_ads = pd.read_csv('/kaggle/input/advertising-simple-dataset/advertising.csv')
import matplotlib.pyplot as plt #Matplotlib为Python画图工具库
import seaborn as sns #Seaborn为统计学数据可视化工具库
#对所有的标签和特征两两显示其相关性的热力图
print (df_ads.corr())
sns.heatmap(df_ads.corr(),cmap="crest", annot = True)
plt.show() #plt代表英文plot, 就是画图的意思
官方示例
Pass a DataFrame
to plot with indices as row/column labels:
import matplotlib.pyplot as plt #Matplotlib为Python画图工具库 import seaborn as sns sns.heatmap(df_ads.corr(), cmap="coolwarm", annot = True) glue = sns.load_dataset("glue").pivot("Model", "Task", "Score") sns.heatmap(glue)
/var/folders/qk/cdrdfhfn5g554pnb30pp4ylr0000gn/T/ipykernel_77613/2862412127.py:1: FutureWarning: In a future version of pandas all arguments of DataFrame.pivot will be keyword-only. glue = sns.load_dataset("glue").pivot("Model", "Task", "Score")
Use annot
to represent the cell values with text:
sns.heatmap(glue, annot=True)
Control the annotations with a formatting string:
sns.heatmap(glue, annot=True, fmt=".1f")
Use a separate dataframe for the annotations:
sns.heatmap(glue, annot=glue.rank(axis="columns"))
Add lines between cells:
sns.heatmap(glue, annot=True, linewidth=.5)
Select a different colormap by name:
sns.heatmap(glue, cmap="crest")
Or pass a colormap object:
sns.heatmap(glue, cmap=sns.cubehelix_palette(as_cmap=True))
tips:
要自定义调色盘,你可以使用
sns.cubehelix_palette()
函数,并将as_cmap
参数设置为True
。这将返回一个颜色映射对象,你可以将其传递给cmap
参数,用于自定义热力图的颜色。
sns.cubehelix_palette()
函数接受多个参数来定义调色盘的外观,例如颜色的亮度、饱和度、开始和结束颜色等。以下是一个示例代码,演示如何使用sns.cubehelix_palette()
自定义调色盘:import seaborn as sns import matplotlib.pyplot as plt # 自定义调色盘 custom_cmap = sns.cubehelix_palette(as_cmap=True) # 绘制热力图并使用自定义调色盘 sns.heatmap(data, cmap=custom_cmap) plt.show()
在这个示例中,我们首先使用
sns.cubehelix_palette()
函数创建一个自定义调色盘,将其赋值给custom_cmap
变量。然后,我们使用sns.heatmap()
函数绘制热力图,并将cmap
参数设置为custom_cmap
,以应用自定义的调色盘。你可以根据需要调整
sns.cubehelix_palette()
函数的参数来获得你想要的调色盘外观。可以参考 seaborn 文档中有关cubehelix_palette()
函数的更多信息:seaborn.cubehelix_palette()。
Set the colormap norm (data values corresponding to minimum and maximum points):
sns.heatmap(glue, vmin=50, vmax=100)
Use methods on the matplotlib.axes.Axes object to tweak the plot:
ax = sns.heatmap(glue, annot=True) ax.set(xlabel="", ylabel="") ax.xaxis.tick_top()