数据科学和科研绘图的人离不开R的ggplot2,尽管python已经有了诸如matplotlib、seaborn等强大绘图包,兼有basemap、cartopy等空间数据可视化能力,但相较于R的ggplot,总感觉欠缺了点东西。
前不久seaborn更新了0.12版本,向ggplot2看齐,可以说是很大的迈进了
此外,整个seaborn的API重写后,操作方式也变化很大,科研人表示要重新开始学习了,不得不感叹开源软件发展的速度,稍微不学习就会落下。
首先更新到新版本:
pip install seaborn==0.12
先以散点图为例,这个add()就像R中的 + geom()…
data = sns.load_dataset('penguins')
data
so.Plot(data, x="bill_length_mm", y="bill_depth_mm").add(so.Dot(), color="species")

在R中比较方便的拟合,现在seaborn也很容易了,只需要so.PolyFit()
tips = sns.load_dataset('tips')
so.Plot(tips, x="total_bill", y="tip", color="time").add(so.Dots()).add(so.Line(), so.PolyFit())

接下来是面积图,这种图经常用于表征极端气候、碳排放的长期变化等等
healthexp = sns.load_dataset('healthexp')
p = so.Plot(healthexp, "Year", "Spending_USD", color="Country")
p.add(so.Line())
p.add(so.Area(), so.Stack())

接下来是散点抖动图,也非常容易
penguins = sns.load_dataset('penguins')
so.Plot(penguins, x="species", y="body_mass_g", color="sex")\
.add(so.Dot(), so.Dodge(), so.Jitter(.3))

so.Plot(healthexp, x="Year", y="Life_Expectancy")\
.facet("Country", wrap=3).add(so.Line(alpha=.3), group="Country", col=None).add(so.Line(linewidth=3))
最后是分面的功能,这在R中非常容易,现在在python中也很方便了

相同的功能,如果用matplotlib,需要以下代码:
# libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd# Make a data frame
df=pd.DataFrame({'x': range(1,11), 'y1': np.random.randn(10), 'y2': np.random.randn(10)+range(1,11), 'y3': np.random.randn(10)+range(11,21), 'y4': np.random.randn(10)+range(6,16), 'y5': np.random.randn(10)+range(4,14)+(0,0,0,0,0,0,0,-3,-8,-6), 'y6': np.random.randn(10)+range(2,12), 'y7': np.random.randn(10)+range(5,15), 'y8': np.random.randn(10)+range(4,14), 'y9': np.random.randn(10)+range(4,14) })# Initialize the figure style
plt.style.use('seaborn-darkgrid')# create a color palette
palette = plt.get_cmap('Set1')# multiple line plot
num=0
for column in df.drop('x', axis=1):num+=1# Find the right spot on the plotplt.subplot(3,3, num)# plot every group, but discretefor v in df.drop('x', axis=1):plt.plot(df['x'], df[v], marker='', color='grey', linewidth=0.6, alpha=0.3)# Plot the lineplotplt.plot(df['x'], df[column], marker='', color=palette(num), linewidth=2.4, alpha=0.9, label=column)# Same limits for every chartplt.xlim(0,10)plt.ylim(-2,22)# Not ticks everywhereif num in range(7) :plt.tick_params(labelbottom='off')if num not in [1,4,7] :plt.tick_params(labelleft='off')# Add titleplt.title(column, loc='left', fontsize=12, fontweight=0, color=palette(num) )# general title
plt.suptitle("How the 9 students improved\nthese past few days?", fontsize=13, fontweight=0, color='black', style='italic', y=1.02)# Axis titles
plt.text(0.5, 0.02, 'Time', ha='center', va='center')
plt.text(0.06, 0.5, 'Note', ha='center', va='center', rotation='vertical')# Show the graph
plt.show()
```plt.text(0.06, 0.5, 'Note', ha='center', va='center', rotation='vertical')# Show the graph
plt.show()

上一篇:抑制细胞代谢紊乱的抑制剂
下一篇:你怎么知道日语句子中汉字的读音?