前面,我们生信技能树的讲师小洁老师与萌老师新开了一个学习班:《掌握Python,解锁单细胞数据的无限可能 》,身为技能树的一员,近水楼台先得月,学起!下面是我的学习笔记,希望可以给你带来一点参考。
前面的学习笔记:
今天继续学习视频:python_day5 !一口气学完吧!
touch day5.ipynb
课前复习到 30:29 plotnine语法 plotnine是python版的ggplot2,有一些细节不同。
示例数据 还是使用的seaborn模块里面的iris数据:
import pandas as pd iris = pd.read_csv("day4/iris.csv" ) iris.head()
安装一下今天需要使用的模块:
# bash终端 conda activate sc pip install plotnine -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple pip install patchworklib -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple
导入模块:这里引入了plotnine里面所有的函数,这样就不需要每次都写plotnine.xx函数。
from plotnine import *
1.入门级绘图模版 需要的数据:横坐标、纵坐标,需要卸载aes的括号里面
(ggplot(data=iris) +
geom_point(aes(x='sepal_length' , y='petal_length' )))
非常具有ggplot2的风格!
2.属性设置 属性包括:
属性 参数 颜色 color 大小 size 形状 shape 透明度 alpha 填充颜色 fill
2.1 统一设置 统一设置需要设为有意义的值。
颜色:字符串,blue,red或者颜色编码(后面介绍)
shape o . , v ^ < > 1 2 3 4 s p * h H + x D d 形状
圆圈 点 像素点 倒三角 正三角 左三角 右三角 下箭头 上箭头 左箭头 右箭头 正方形 五角形 星号 六边形 另一种六边形 加号 叉号 菱形 瘦菱形
修改颜色:color='blue'(ggplot(data=iris) + geom_point(aes(x='sepal_length' , y='petal_length' ), color='blue' ))
修改其他属性 size=5、alpha=0.5、shape='*'(ggplot(data=iris) + geom_point(aes(x='sepal_length' , y='petal_length' ), size=5 , # 点的大小5mm alpha=0.5 , # 透明度 50% shape='*' )) # 点的形状
2.2 映射:按照数据框的某一列来定义图的某个属性 根据“species”列来定义“颜色”这个属性,即:相同的值是相同的颜色,不同的值对应不同的颜色,有三个值所以自动分配了三种颜色。
note:需要写到aes括号里面。
(ggplot(data=iris) + geom_point(aes(x='sepal_length' , y='petal_length' , color='species' )))
2.2.1 自行指定映射的具体颜色可以使用 scale_xx_manual 的函数
具体的颜色名:
(ggplot(data=iris) + geom_point(aes(x='sepal_length' , y='petal_length' , color='species' )) + scale_color_manual(values=['blue' , 'green' , 'red' ]))
颜色编码:
# 十六进制颜色 (ggplot(data=iris) + geom_point(aes(x='sepal_length' , y='petal_length'
, color='species' )) + scale_color_manual(values=['#2874C5' , '#e6b707' , '#f87669' ]))
2.2.2 最好的配色库pypalettes上一节课也出现了这个配色网址:在这里看有哪些配色,2500+种!https://python-graph-gallery.com/color-palette-finder/
import pypalettes cs = pypalettes.load_cmap('Abbott' ) cs.colors (ggplot(data=iris) + geom_point(aes(x='sepal_length' , y='petal_length' , color='species' )) + scale_color_manual(values=cs.colors))
很方便换主题:
# 直接在这里换主题即可 pypalettes.load_cmap('a_palette' )
2.2.3 区分color和fill参数# 实心形状,用color设置颜色 (ggplot(data=iris) + geom_point(aes(x='sepal_length' , y='petal_length' , color='species' ), shape='^' ,size = 3 ))
空心:fill = 'none'
shape='h':六边形
# 空心形状,fill = 'none' (ggplot(data=iris) + geom_point(aes(x='sepal_length' , y='petal_length' , color='species' ), shape='h' ,size = 3 , fill='none' ))
同时设置边框和填充色:红绿搭配,干活不累,哈哈哈哈
# 双色,color设置边框颜色,fill设置填充颜色 (ggplot(data=iris) + geom_point(aes(x='sepal_length' , y='petal_length' ), shape='^' , color='red' , fill='green' , size = 3 ))
3.几何对象 几何对象:geom_
开头的函数
可以在同一个图里面面叠加多个几何对象,但是代码变得罗嗦了:写了两遍aes(x='sepal_length', y='petal_length')。
(ggplot(data=iris) + geom_smooth(aes(x='sepal_length' , y='petal_length' )) + geom_point(aes(x='sepal_length' , y='petal_length' )))
简化:将aes(x='sepal_length', y='petal_length')放在ggplot括号里
(ggplot(data=iris, mapping=aes(x='sepal_length' , y='petal_length' )) + geom_smooth() + geom_point())
4.位置调整 geom_point()
:相同位置的点重叠在一起,信息被隐藏
(ggplot(data=iris, mapping=aes(x='species' , y='sepal_width' )) + geom_boxplot(aes(fill='species' ),alpha = 0.5 ) + geom_point())
解决办法:使用 geom_jitter
函数
(ggplot(data=iris, mapping=aes(x='species' , y='sepal_width' )) + geom_boxplot(aes(fill='species' ),alpha = 0.5 ) + geom_jitter())
5.坐标系 使用coord_flip()
进行坐标轴翻转:
(ggplot(data=iris, mapping=aes(x='species' , y='sepal_width' )) + geom_boxplot(aes(fill='species' ),alpha = 0.5 ) + geom_jitter() + coord_flip()) #横纵坐标互换
6.主题 改一个试试:theme_bw()
# theme_bw() (ggplot(data=iris, mapping=aes(x='species' , y='sepal_width' )) + geom_boxplot(aes(fill='species' ),alpha = 0.5 ) + geom_jitter() + theme_bw())
theme_classic()
:
# theme_classic() (ggplot(data=iris, mapping=aes(x='species' , y='sepal_width' )) + geom_boxplot(aes(fill='species' ),alpha = 0.5 ) + geom_jitter() + theme_classic())
7.保存 使用ggsave()
:
p = (ggplot(data=iris, mapping=aes(x='species' , y='sepal_width' , fill='species' )) + geom_boxplot(alpha = 0.5 ) + geom_jitter() + theme_bw()) ggsave(p,filename="boxplot.png" )
8.拼图 使用 patchworklib
模块:
import patchworklib as pw p1 = (ggplot(data=iris) + geom_point(aes(x='sepal_length' , y='petal_length' ))) p2 = (ggplot(data=iris) + geom_boxplot(aes(x='species' , y='sepal_length' )))# 使用patchworklib加载plotnine图表 g1 = pw.load_ggplot(p1, figsize=(2 ,3 )) g2 = pw.load_ggplot(p2, figsize=(2 ,3 )) g1|g2
下一个知识点 讲解 01:42:28 1.NA缺失值 1.1 判断是否是缺失值 在python中,NaN
、NULL
、NA
、None
都是缺失值的意思,但在R语言:
NaN
表示非数值(Not a Number),计算0/0
或者计算负数的平方根时会得出。
含缺失值的数据集非常常见。写代码时提到缺失值要写None
或者是np.NaN
,np.NAN
,np.nan
。
构造一个含有缺失值的数据框:写的时候是None,但是显示为NaN,python中这两者不区分。
import pandas as pd df = pd.DataFrame({'gene' :['gene1' ,'gene2' ,'gene3' ], 'sample1' :[None ,16.0 ,3.0 ], 'sample2' :[2 ,11 ,1 ]}) print(df)
# 判断是否含有缺失值 pd.isna(df.sample1)# 统计有多少个缺失值 df['sample1' ].isna().value_counts()
1.2 插补缺失值 .fillna()
函数 :将列中的所有缺失值替换为提供的值。
例如:将 sample1 列里面的 NA 填充上该列的平均值,传递给 f 列:
df['sample1_f'
] = df['sample1' ].fillna(df['sample1' ].mean()) print(df)
2.Apply 和自定义函数 计算每行/每列的函数运算结果,例如平均值
python 里的apply
是axis = 1
表示行,0
表示列, 0是
默认值
2.1 示例数据 使用 pandas 构建一个数据框:
import pandas as pdimport numpy as np# 固定随机种子,保证结果可复现 np.random.seed(42 ) df = pd.DataFrame({ 'student_id' : range(1 , 11 ), # 学生ID 'student_group' :['group1' ]*5 +['group2' ]*5 , 'math_score' : np.random.randint(50 , 100 , 10 ), # 数学分数 'english_score' : np.random.randint(50 , 100 , 10 ), # 英语分数 }) print(df)
2.2 apply + 现有的函数 # 两列求方差 df[['math_score' ,'english_score' ]].apply('var' ) # 每一行求标准差 df[['math_score' ,'english_score' ]].apply('std' ,axis = 1 ) # 现有函数 df[['math_score' ,'english_score' ]].std(axis=1 )
2.3 apply + 自定义函数 自定义一个函数:
def calculate_grade (score) : if score >= 90 : return 'A' elif score >= 80 : return 'B' elif score >= 70 : return 'C' elif score >= 60 : return 'D' else : return 'F'
3.groupby 完成分组计算 例如:计算 group1 和 group2 组的学生数学平均分是多少
import pandas as pdimport numpy as np# 固定随机种子,保证结果可复现 np.random.seed(42 ) df = pd.DataFrame({ 'student_id' : range(1 , 11 ), # 学生ID 'student_group' :['group1' ]*5 +['group2' ]*5 , 'math_score' : np.random.randint(50 , 100 , 10 ), # 数学分数 'english_score' : np.random.randint(50 , 100 , 10 ), # 英语分数 }) print(df) df.groupby('student_group' )['math_score' ].mean()
agg()
函数:
# 计算group1和group2组学生的数学分数的最小值、最大值、和 # 一列 print(df.groupby("student_group" )["math_score" ].agg(['min' , 'max' , 'sum' ]))# 多列:数学 和英语 result = df.groupby("student_group" ).agg({ "math_score" : ["min" , "max" , "sum" ], "english_score" : ["min" , "max" , "sum" ] }) print(result)
4.综合应用 4.1 批量读取文件 index_col=0
:第一列读取为行名
import osimport pandas as pd files = os.listdir('day5/raw_data' ) print(files)# 使用`for`循环读取 result = []for x in files: result.append(pd.read_table("day5/raw_data/" +x,index_col=0 ,header = None ,names = [x])) print([x.shape for x in result])
使用推导式去读
import osimport pandas as pd files = os.listdir('day5/raw_data' ) print(files)# 使用推导式完成读取 result2 = [pd.read_table("day5/raw_data/" +x,index_col=0 ,header = None ,names = [x]) for x in files] print([x.shape for x in result2])# 查看一个文件内容 print(result2[0 ].head())
4.2 合成一个表达矩阵 使用 pd.concat()
函数,axis=1
按照列合并
re = pd.concat(result2, axis=1 ) print(re.head()) print(re.iloc[0 :4 ,0 :4 ])
4.3 清除不以ENSG开头的行 re = re[re.index.str.startswith('ENSG' )] re.shape
4.4 找出方差最大的10个基因 re.var(axis = 1 ).sort_values(ascending = False ).head(10 ).index
更简洁的办法:
genes = re.var(axis = 1 ).nlargest(10 ).index print(genes) genes = re.var(axis = 1 ).nlargest(10 ) print(genes)
第五天的视频刷完~
文末友情宣传: 生信入门&数据挖掘线上直播课2025年1月班
时隔5年,我们的生信技能树VIP学徒继续招生啦
满足你生信分析计算需求的低价解决方案