seaborn官方文档的一些坑(以tips为例)

初次接触seaborn的一个问题

Seaborn 是一个基于 matplotlib 且数据结构与 pandas 统一的统计图制作库。主要特点是画风优良,图形类别更加多样,但数据结构依赖pandas库,比matplotlib.pyplot少了一份简洁。在此记录刚接触seaborn的一个小问题。

如何获取官网所说的内置数据?

在seaborn官网的Introduction中,会有这样一个栗子作为开篇:

import seaborn as sns
sns.set()
tips = sns.load_dataset("tips")
sns.relplot(x="total_bill", y="tip", col="time",
            hue="smoker", style="smoker", size="size",
            data=tips);

依官网所言,将会出现以下图片:
seaborn官方文档的一些坑(以tips为例)_第1张图片
但实际上会出现以下错误
urllib.error.URLError:
原因是因为这些数据要从外网下载,如果没有梯子的话将会无法访问。
故在此提供一些截取于‘tips’的数据(源数据约240行),供大家操作:

total_bill,tip,sex,smoker,day,time,size 
16.99,1.01,Female,No,Sun,Dinner,2
10.34,1.66,Male,No,Sun,Dinner,3
21.01,3.5,Male,No,Sun,Lunch,3
23.68,3.31,Male,Yes,Sat,Dinner,2
24.59,3.61,Female,No,Sun,Dinner,4
30,5,Female,No,Sat,Dinner,6
29,3,Male,Yes,Sat,Dinner,5
28,3.5,Male,No,Sun,Lunch,6
10,3.31,Male,No,Sun,Dinner,1
9,3.61,Female,Yes,Sat,Dinner,1
64,10,Female,Yes,Sun,Dinner,8
30,4,Male,Yes,Sat,Lunch,5
20,5,Male,Yes,Sun,Dinner,3
24,4,Male,No,Sat,Lunch,4
18,3,Female,No,Sun,Dinner,2
17,1,Female,No,Sat,Dinner,3
16,2,Male,No,Sat,Dinner,2
19,2,Male,No,Sun,Lunch,2
23,4,Male,No,Sun,Dinner,3
22,2,Female,Yes,Sat,Dinner,3
30,1.01,Female,No,Sun,Dinner,5
40,1.66,Male,No,Sun,Dinner,5
33,3.5,Male,No,Sun,Lunch,5
35,18,Male,Yes,Sat,Dinner,6
36,3.61,Female,No,Sun,Dinner,5
38,5,Female,No,Sat,Dinner,5
42,15,Male,Yes,Sat,Dinner,6
44,3.5,Male,No,Sun,Lunch,6
49,3.31,Male,No,Sun,Dinner,5
46,10,Female,Yes,Sat,Dinner,6
47,20,Female,Yes,Sun,Dinner,6
43,11,Male,Yes,Sat,Lunch,7
61,12,Male,Yes,Sun,Dinner,5
51,6,Male,No,Sat,Lunch,8
52,8,Female,No,Sun,Dinner,7
58,8,Female,No,Sat,Dinner,7
55,8,Male,No,Sat,Dinner,8
57,5,Male,No,Sun,Lunch,7
53,6,Male,No,Sun,Dinner,8
62,14,Female,Yes,Sat,Dinner,10

读取方式

对于本地数据,不可用seaborn的load_dataset()方法操作:

import pandas as pd
import seaborn as sns
#引号内为文件地址
tips = pd.read_csv("tips.csv")  #如果文件类型是CSV文件
tips = pd.read_table('tips.txt', sep=',') #如果文件类型是txt

然后我们尝试下按照官网所说的方法画图:

sns.relplot(x="total_bill", y="tip", col="time",
            hue="smoker", style="smoker", size="size",
            data=tips);

祸不单行

然而祸不单行,又出现了error:
ValueError: Could not interpret input 'size'
我们可以从官网了解到relplot函数的参数都是控制图像要素的,比如颜色,x轴,y轴,图标尺寸等等,都是来源于参数data,也就是数据集,这里就是tips。这些控制要素的参数要么是一个属于数据的某一列的名字(字符串),要么是数据的一列,例如:

sns.relplot(x=tips.total_bill, y=tips.tip, col=tips.time,
            hue=tips.smoker, style=tips.smoker, size=tips.size,
            data=tips);

上述写法等效于官网给出写法。
所以可以看出来,之所以size处行不通,是因为出于巧合,tips.size恰好是该数据的一个属性,即数据集的大小,而不是一个列的数据。

解决方案

显然我们要传入一个实实在在的行数据,但是又不能通过文字索引,故只有数字索引行得通

ns.relplot(x="total_bill", y="tip", col="time",
            hue="smoker", style="smoker", size=tips.iloc[:,-1],
            data=tips)
plt.plot()

然后出现图片:
seaborn官方文档的一些坑(以tips为例)_第2张图片
大功告成!
最后给大家分享一个seaborn官网汉化版网址:https://www.cntofu.com/book/172/index.html
虽然其中只有部分文档汉化完成,但帮助还是蛮大的。

你可能感兴趣的:(python)