转载自:https://www.jianshu.com/p/4d7d7e4ff4f8
基于python的拟合线置信区间
首先看下本文作者用自己数据基于python出来的图


注:第二张图例的slope和p值是后期p上去,第一张图是基于python,第二张是基于R
本文引入python的第三方库seaborn进行绘制,库的安装可使用pip install seaborn命令进行安装。具体如下:
(1)推荐安装Anaconda,具体软件的链接自行百度
(2)选择图中的红线部分,打开后在里面输入pip install seaborn即可以安装成功了

打开里面的Spyder程序,通过file-new file新建脚本,输入以下命令即可
import seaborn as sns
tips = sns.load_dataset("tips") #导入sns中自带的数据集
sns.regplot(x="total_bill",y="tip",data=tips)
结果如下:

如果说我们的数据格式是excel的,先另存为csv格式的
然后用如下代码:
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
plt.figure(figsize=(5, 5)) #设置图片的长和宽
data = pd.read_csv(u'D://test.csv') #读取存放的文件
sns.regplot(x="total_bill",y="tip",data=data)
结果如下

上面的图片结果中的分辨率较低,后续需要进一步保存为高质量的图片。主要是加入plt.savefig命令完整代码如下
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
data = pd.read_csv(u'D://test.csv') #读取存放的文件
plt.figure(figsize=(5, 5))
sns.regplot(x="total_bill",y="tip",data=data)
plt.savefig(u'D://test.pdf')
结果如下:

建议大家安装Adobe Acrobat Pro版本的pdf编辑器,能够对pdf进行再次编辑,调整里面的字体和大小及颜色等,简直神器。
当我们需要进行分两组进行拟合,并要将结果显示在同一张图时,采用lmplot函数并增加一个参数hue就能实现,具体如下
import seaborn as sns
from matplotlib import pyplot as plt
tips = sns.load_dataset("tips")
plt.figure(figsize=(5, 5))
sns.lmplot(x="total_bill",y="tip",hue="sex",data=tips)
plt.savefig(u'D://test2.pdf')
结果如下:

在D盘下面也会生成test2.pdf这个文件。但当分组类别比较多的时候就不适用于把这么多组放在同一张图里面,此时如何做呢?
答案是将上述代码中的hue改为col即可,
import seaborn as sns
from matplotlib import pyplot as plt
tips = sns.load_dataset("tips")
plt.figure(figsize=(5, 5))
sns.lmplot(x="total_bill",y="tip",col="sex",data=tips)
plt.savefig(u'D://test2.pdf')
结果如下

通过上述代码遍能够生成pdf格式的带拟合线置信区间的折线图了,然后用ps打开pdf便可以随意设置分辨率。
注意:目前如何调出拟合线的方程并自动添加R2本人还没有做出来,需要后续通过ps将R2和方程给p上去。
作者最后用自己的数据生成代码如下:
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
data = pd.read_csv(u'D:\haihe.csv') #读取存放的文件
plt.figure(figsize=(10, 6))
sns.lmplot(x="year",y="value",data=data,hue="type")
plt.savefig(u'D://haihe.pdf')
数据格式请参考上述代码中的tips数据集的格式
作者:画长空_yin
链接:https://www.jianshu.com/p/4d7d7e4ff4f8
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。