欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Seaborn学习以及Matplotlib基础(持续更新中...)

程序员文章站 2022-03-19 10:53:38
...

matplotlib基础

plt.plot(first_twelve['DATE'], first_twelve['VALUE'])
plt.xticks(rotation=45)
plt.xlabel('Month')
plt.ylabel('Unemployment Rate')
plt.title('Monthly Unemployment Trends, 1948')
plt.legend(loc='best')

画子图:

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(3, 3))
ax1 = fig.add_subplot(3,2,1)
ax2 = fig.add_subplot(3,2,2)
ax3 = fig.add_subplot(3,2,6)
ax1.plot(…)
ax2.plot(…)
ax3.plot(…)
plt.show()

先生成一个画布(fig),然后生成一系列子图,ax1,ax2,ax3,然后操作ax进行绘图,最后show出来画布(fig)

Pandas

food_info = pandas.read_csv("food_info.csv")
food_info.dtypes
food_info.head(3)
food_info.tail(4)
food_info.columns
food_info.shape
col_names = food_info.columns.tolist()

Selection by Label

df.loc 
df.loc[:,[‘A’,’B’]] 
df.loc[‘20130102’:’20130104’,[‘A’,’B’]]

Selection by Position

df.iloc[3:5,0:2] 
df.iloc[[1,2,4],[0,2]]

Boolean Indexing

df[df.A > 0]df[df > 0]df2[df2[‘E’].isin([‘two’,’four’])]

Setting a new column

s1=pd.Series([1,2,3,4,5,6], index=pd.date_range(‘20130102’, periods=6));df[‘F’] = s1; 
df.loc[:,’D’] = np.array([5] * len(df)) 
df2[df2 > 0] = -df2

单个赋值

df.iat[0,1] = 0 
df.at[dates[0],’A’] = 0

缺失值处理

df1.dropna(how=’any’) 
df1.fillna(value=5) 
pd.isna(df1)
new_titanic_survival = titanic_survival.dropna(axis=0,subset=["Age", "Sex"])

坍塌到横向

df.mean(axis=’rows’)

坍塌到纵向


df.mean(axis=’columns’)  


统计数目(获取数据的BigIdea

s.value_counts())

字符串处理
正则表达式:@

时间序列的处理

Pandas-3

排序

food_info.sort_values("Sodium_(mg)", inplace=True, ascending=False)

检测空值,返回bool类型

pd.isnull(age)

pivot_table 函数

passenger_survival = titanic_survival.pivot_table(index="Pclass", values="Survived", aggfunc=np.mean)

pivot table中的index参数,有点类似与groupby的功能
index tells the method which column to group by
values is the column that we want to apply the calculation to
aggfunc specifies the calculation we want to perform

处理缺失值:
@

排序完之后一般需要重置index

ew_titanic_survival.reset_index(drop=True)
df1 = df.reindex(index=dates[0:4], columns=list(df.columns) + [‘E’]) 
s = pd.Series([1,3,5,np.nan,6,8], index=dates).shift(2)

连续数据离散化&apply函数:
By passing in the axis=1 argument, we can use the DataFrame.apply() method to iterate over rows instead of columns.

def which_class(row):
    pclass = row['Pclass']
    if pd.isnull(pclass):
        return "Unknown"
    elif pclass == 1:
        return "First Class"
    elif pclass == 2:
        return "Second Class"
    elif pclass == 3:
        return "Third Class"
classes = titanic_survival.apply(which_class, axis=1)

Dtype汇总

#A Series object can hold many data types, including
#float - for representing float values
#int - for representing integer values
#bool - for representing Boolean values
#datetime64[ns] - for representing date & time, without time-zone
#datetime64[ns, tz] - for representing date & time, with time-zone
#timedelta[ns] - for representing differences in dates & times (seconds, minutes, etc.)
#category - for representing categorical values
#object - for representing String values

取出pd中的值

rt_scores = series_rt.values

对于series格式的排序

sc2 = series_custom.sort_index()
sc3 = series_custom.sort_values()

Seaborn库

Seaborn-1Style

sns.set();sns.set(rc={"figure.figsize": (6, 6)})
sns.set_context("paper");sns.set_context("talk");sns.set_context("poster")
sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5})
sns.set_style("whitegrid")
plt.figure(figsize=(8, 6))

5种主题风格
• darkgrid
• whitegrid
• dark
• white
• ticks

图形的绘制

sns.violinplot(data)
sns.boxplot(data=data, palette="deep")

坐标轴的一些设置(隐藏、距离)
子图绘制

Seaborn-2 ColorPlatte

分类色板
6个默认的颜色循环主题: deep, muted, pastel, bright, dark, colorblind
圆形画板
当你有六个以上的分类要区分时,最简单的方法就是在一个圆形的颜色空间中画出均匀间隔的颜色(这样的色调会保持亮度和饱和度不变)。这是大多数的当他们需要使用比当前默认颜色循环中设置的颜色更多时的默认方案。
连续色板
色彩随数据变换,比如数据越来越重要则颜色越来越深

Seaborn-3Var

直方图

sns.distplot(x, kde=False, fit=stats.gamma)

观察两个变量之间的关系:

sns.jointplot(x="x", y="y", data=df);
sns.jointplot(x=x, y=y, kind="hex", color="k")

一次性观察两两特征之间的关系

sns.pairplot(iris)

Seaborn4-REG

两个变量回归作图:

sns.regplot(x="total_bill", y="tip", data=tips)

含有三个属性的回归作图:
其中hue为category变量

sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips,
           markers=["o", "x"], palette="Set1");

含有四、五个属性(两个连续,两、三个是category变量)的回归作图:

sns.lmplot(x="total_bill", y="tip", hue="smoker",
           col="time", row="sex", data=tips);

在指定的axis上画图:

f, ax = plt.subplots(figsize=(5, 5))
sns.regplot(x="total_bill", y="tip", data=tips, ax=ax);

Seaborn5-category

观察数据在category型变量上的分布

sns.stripplot(x="day", y="total_bill", data=tips, jitter=True)
sns.swarmplot(x="day", y="total_bill", data=tips)

三维属性:加入hue

sns.swarmplot(x="day", y="total_bill", hue="sex",data=tips)

盒图

sns.boxplot(x="day", y="total_bill", hue="time", data=tips);

小提琴图

sns.violinplot(x="total_bill", y="day", hue="time", data=tips);
sns.violinplot(x="day", y="total_bill", hue="sex", data=tips, split=True);

条形图

sns.barplot(x="sex", y="survived", hue="class", data=titanic);

显示值的集中趋势可以用条形图
x为category变量;y为连续型变量

点图

sns.pointplot(x="sex", y="survived", hue="class", data=titanic);

点图可以更好的描述变化差异

sns.pointplot(x="class", y="survived", hue="sex", data=titanic,
              palette={"male": "g", "female": "m"},
              markers=["^", "o"], linestyles=["-", "—"]);

Seaborn中将以上的作图函数综合到了一个函数中:

seaborn.factorplot(x=None, y=None, hue=None, data=None, row=None, col=None, col_wrap=None, estimator=, ci=95, n_boot=1000, units=None, order=None, hue_order=None, row_order=None, col_order=None, kind='point', size=4, aspect=1, orient=None, color=None, palette=None, legend=True, legend_out=True, sharex=True, sharey=True, margin_titles=False, facet_kws=None, **kwargs)

Parameters:
• x,y,hue 数据集变量 变量名
• date 数据集 数据集名
• row,col 更多分类变量进行平铺显示 变量名
• col_wrap 每行的最高平铺数 整数
• estimator 在每个分类中进行矢量到标量的映射 矢量
• ci 置信区间 浮点数或None
• n_boot 计算置信区间时使用的引导迭代次数 整数
• units 采样单元的标识符,用于执行多级引导和重复测量设计 数据变量或向量数据
• order, hue_order 对应排序列表 字符串列表
• row_order, col_order 对应排序列表 字符串列表
• kind : 可选:point 默认, bar 柱形图, count 频次, box 箱体, violin 提琴, strip 散点,swarm 分散点 size 每个面的高度(英寸) 标量 aspect 纵横比 标量 orient 方向 “v”/”h” color 颜色 matplotlib颜色 palette 调色板 seaborn颜色色板或字典 legend hue的信息面板 True/False legend_out 是否扩展图形,并将信息框绘制在中心右边 True/False share{x,y} 共享轴线 True/False

Seaborn 7-Heatmap

data是一个二维的矩阵

heatmap = sns.heatmap(data)

调整右侧colorbar的参数

vmin=0.2, vmax=0.5,center=0

将数据整理成二维的再画热度图:

flights = flights.pivot("month", "year", "passengers")
ax = sns.heatmap(flights,annot=True,fmt="d",linewidths=.5)

画置信区间带(timeseries数据)
Plot one or more timeseries with flexible representation of uncertainty.This function is intended to be used with data where observations are nested within sampling units that were measured at multiple timepoints.

sns.tsplot()