目录

  • 概述
  • 基础
  • 种类(Sample plots in Matplotlib)
  • 散点图(Scatter plots)
  • 椭圆图
  • 线图(Line plot)
  • 直方图(Bar charts)
  • 柱状图的种类及作图
  • 频率分布直方图(Histograms)
  • 表格直方图(Tables)
  • 饼图(Pie charts)
  • 轮廓线和伪彩色(Contouring and pseudocolor)
  • 极坐标(Ploar plots)
  • 3D
  • 图例(legend)
  • 其他很多
  • 布局
  • 方式一
  • 方式二
  • 总结
  • 风格(Styles)
  • 颜色(Colors)
  • Tips
  • 分析杂志记录:
  • 表达差异基因分析:
  • 差异表达基因的聚类热图:
  • 差异基因venn图:
  • 导出


概述

# Version 
	pip install matplotlib=3.42

基础

matplotlib绘图原理:在画布(figure)上绘制坐标系(axes),其中各个元素标识如下:

Python plot头尾连起来了_图例

种类(Sample plots in Matplotlib)

散点图(Scatter plots)

scatter()

Python plot头尾连起来了_Python plot头尾连起来了_02

椭圆图

Phoenix

Python plot头尾连起来了_直方图_03

线图(Line plot)

plot()

Python plot头尾连起来了_图例_04

直方图(Bar charts)

bar()

Python plot头尾连起来了_Python plot头尾连起来了_05

柱状图的种类及作图

import matplotlib.pyplot as plt
	
	fig, ax = plt.subplot(figsize(10, 10))

频率分布直方图(Histograms)

hist()

Python plot头尾连起来了_数据可视化_06

表格直方图(Tables)

tables()

Python plot头尾连起来了_直方图_07

饼图(Pie charts)

pie()

Python plot头尾连起来了_直方图_08

轮廓线和伪彩色(Contouring and pseudocolor)

pcolormesh()contour()

Python plot头尾连起来了_图例_09

极坐标(Ploar plots)

ploar()

Python plot头尾连起来了_直方图_10

3D

3D ploting

Python plot头尾连起来了_图例_11

图例(legend)

legend()

Python plot头尾连起来了_Python plot头尾连起来了_12

其他很多

布局

方式一

plt.subplot() 只是返回一个 Ax

fig = plt.figure(figsize=(3, 5)) # 画布及大小
ax1 = plt.subplot(221)
ax2 = plt.subplot(222)
ax3 = plt.subplot(223)
ax4 = plt.subplot(224)

或者

fig = plt.figure(figsize=(3, 5)) # 画布及大小
   	ax1 = fig.add_subplot(221)
   	ax1.set_title('Ax1')
   
   	ax2 = fig.add_subplot(222)
   	ax2.set_title('Ax2')
   
   	ax3 = fig.add_subplot(223)
   	ax3.set_title('Ax3')
   
   	ax4 = fig.add_subplot(224)
   	ax4.set_title('Ax4')

结果均如下

Python plot头尾连起来了_直方图_13

方式二

plt.subplots() 返回元组形式的 fig和Ax

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(19680801)
data = np.random.randn(2, 100)

fig, axs = plt.subplots(2, 2, figsize=(5, 5))
axs[0, 0].hist(data[0])
axs[0, 0].set_title('hist')

axs[1, 0].scatter(data[0], data[1])
axs[1, 0].set_title('line')

axs[0, 1].plot(data[0], data[1])
axs[0, 1].set_title('scatter')

axs[1, 1].hist2d(data[0], data[1])
axs[1, 1].set_title('psecolor')

plt.show()

或者

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(19680801)
data = np.random.randn(2, 100)

fig, ((axs1, axs2), (axs3, axs4)) = plt.subplots(2, 2, figsize=(5, 5))
axs1.hist(data[0])
axs1.set_title('hist')

axs2.scatter(data[0], data[1])
axs2.set_title('line')

axs3.plot(data[0], data[1])
axs3.set_title('scatter')

axs4.hist2d(data[0], data[1])
axs4.set_title('psecolor')

均如下结果

Python plot头尾连起来了_图例_14

总结

  1. plt.subplot()或在已定义的fig中用fig.add_subplot(),这两种方式都只是返回一个ax类。好处是可以设置某几个子图公用y轴或x轴(sharex=,sharey=),但操作麻烦;
  2. plt.subplots()是预先定义好所有子图个数及布局后一次性返回fig和ax两个类;

风格(Styles)

print(plt.style.available)

Python plot头尾连起来了_python_15

plt.style.use('dark_background')
plt.tight_layout() # 很好用

颜色(Colors)

Tips

# -*- coding: utf-8 -*-
"""
Created on Wed Jun 24 13:51:48 2020

@author: Bio-windows
"""

import numpy as np
import matplotlib.pyplot as plt

#数据
x = np.linspace(0.05, 10, 100)
y = np.cos(x)

#绘图
plt.plot(x, y, ls="-", lw=2, label="plot figure")
plt.scatter(x, y,label="scatter figure")

#坐标轴范围、标签
plt.xlim(-10, 20)
plt.xlabel("Time(seconds)")
plt.ylim(-2, 2)
plt.ylabel("Signal")

#标题
plt.title("Hello")
#图例
plt.legend(loc="upper left")
#网格
plt.grid(linestyle=":", color="r") #:->虚线,红色
#水平参考线
plt.axhline(y=0, ls=":", lw=2, c="g") #c=color,ls=line style,lw=line width
#水平参考区域
plt.axhspan(ymin=-0.5, ymax=0.5, facecolor="r", alpha=0.3) #facecolor填充颜色,alpha透明度
#垂直参考线
plt.axvline(x=5, ls=":", lw=3, c="b") #c=color,ls=line style,lw=line width
#垂直参考区域
plt.axvspan(xmin=1.5, xmax=6.5, facecolor="y", alpha=0.3)
#注释,函数annotate()一一添加图形内容细节的指向型注释文本
plt.annotate("This is the annotation", xy=(5, np.cos(5)), xytext=(6, np.cos(6)), arrowprops=dict(arrowstyle="->", connectionstyle="arc3", color="b"))
#函数text()一一添加图形内容细节的无指向型注释文本
plt.text(-5, np.cos(-5), "This is the text")


plt.show()

Python plot头尾连起来了_Python plot头尾连起来了_16

分析杂志记录:

fig, ax = plt.subplots(figsize=[5, 9])
ax.plt(x, y)
ax.set_title('Title')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_axvline(x=? , ls=":", lw=3, c="b") #
ax1 = ax.twinx() #ax1和ax公用x轴
ax1 = ax.twiny() #ax1和ax公用y轴
ax1.scatter(x= , y= )
ax1.set_xlabel('X1')
ax1.set_ylaber('Y1')

Python plot头尾连起来了_直方图_17

表达差异基因分析:

# -*- coding: utf-8 -*-
"""
Created on Fri Jul 24 10:50:31 2020

@author: Bio-windows
"""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

#read DEG.xls file
deg = pd.read_table('DEG.xls')

pValue_threshold = 0.00000000000001
FoldChange_threshold = 1



#Up and Down regulation genes
deg['ChangeMode'] = 'silver'
deg.loc[ (deg['log2.Fold_change.'] > FoldChange_threshold) & (deg['p.value'] < pValue_threshold), 'ChangeMode'] = 'red'
deg.loc[ (deg['log2.Fold_change.'] < -FoldChange_threshold) & (deg['p.value'] < pValue_threshold), 'ChangeMode'] = 'blue'


#Graphic building
fig, ax = plt.subplots()
ax.scatter(x=deg['log2.Fold_change.'], y=-np.log10(deg['p.value']), s=2, c=deg['ChangeMode'])
ax.set(ylabel='-log10(pValue)', xlabel='FoldChange', title='DeffExpGenes')
ax.set(xlim=(-10, 10), ylim=(0, 300))
ax.hlines(-np.log10(pValue_threshold), xmin=-10, xmax=10, color='dimgrey',linestyle='dashed', linewidth=1) #画竖水平线
ax.vlines(-FoldChange_threshold, ymin=0, ymax=250, color='dimgrey',linestyle='dashed', linewidth=1) #画竖直线
ax.vlines( FoldChange_threshold, ymin=0, ymax=250, color='dimgrey',linestyle='dashed', linewidth=1) #画竖直线

#整体调整
ax.spines['right'].set_visible(False) #remove right spines
ax.spines['top'].set_visible(False) #remove top spines


#save figures
plt.savefig('fig.pdf')

Python plot头尾连起来了_图例_18

差异表达基因的聚类热图:

# -*- coding: utf-8 -*-
"""
Created on Fri Jul 24 14:13:41 2020

@author: Bio-windows
"""
import pandas as pd
import seaborn as sns

#read data files
ven = pd.read_excel('ven.xls')
ven1 = ven.set_index('genes')
#drawing
sns.clustermap(ven1)

Python plot头尾连起来了_直方图_19


Python plot头尾连起来了_Python plot头尾连起来了_20

差异基因venn图:

导出

matplotlib.rcParams['pdf.fonttype'] = 42 # Export pdf with Adobe Illust.. format
matplotlib.rcParams['ps.fonttype'] = 42 # Export pdf with Adobe Illust.. format

plt.rcParams['font.sans-serif']=['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False # 用来正常显示负号