Python patchworklib任意合并子图,多图形混合排版

2023-12-24 12:55:46

【背景】

数据展示时,在同一页面上混合排版多个图形是一种常见的用法。本次分享一个Python轮子patchworklib库:通过|、/轻松实现图形排列;比matplotlib、seaborn等自带子图功能更加灵活;

【patchworklib简介】

Patchworklib 是与 matplotlib 相关的绘图(简单 matplotlib 绘图、Seaborn 绘图(轴级和图形级)和plotnine 绘图)的通用编辑器。这个库的灵感来自于 ggplot2 的patchwork。因此,作为原始拼凑,用户可以轻松地仅使用/和|对齐 matplotlib 图。

使用前需要用命令安装:

pip3?install?patchworklib

【案例1-结合matplotlib】在Matplotlib中使用patchworklib拼图

主要使用pw.Brick方法savefig方法

import?patchworklib?as?pw
import?matplotlib.pyplot?as?plt
plt.style.use('ggplot')#绘制子图1
ax1?=?pw.Brick(figsize=(1,?2))??#每个子图调用pw.Brick方法
ax1.bar([1,?2],?[1,?2])
ax1.set_title("ax1")#绘制子图2
ax2?=?pw.Brick(figsize=(1,?3))
ax2.scatter(range(5),?range(5))
ax2.set_title("ax2")#绘制子图3
ax3?=?pw.Brick(figsize=(2,?1))
ax3.bar([2,?1],?[2,?3])
ax3.set_title("ax3")#绘制子图4
ax4?=?pw.Brick(figsize=(2,?2))
ax4.scatter(range(5),?range(5))
ax4.set_title("ax4")#拼图
ax1234?=?(ax1?|?ax2)?|?(ax3?/?ax4)
ax1234.savefig()??#类似plt.show()

11d32acd1db5af8412f19c0a5221710d.png

【案例2-结合seaborn】 在seaborn中使用patchworklib拼图

import?patchworklib?as?pw
import?seaborn?as?sns?

fmri?=?sns.load_dataset("fmri")
ax1?=?pw.Brick(figsize=(3,2))
sns.lineplot(x="timepoint",?y="signal",?hue="region",?style="event",?data=fmri,?ax=ax1)
ax1.legend(bbox_to_anchor=(1.05,?1.0),?loc='upper?left')
ax1.set_title("ax1")
?
titanic?=?sns.load_dataset("titanic")
ax2?=?pw.Brick(figsize=(1,2))
sns.barplot(x="sex",?y="survived",?hue="class",?data=titanic,?ax=ax2)
ax2.move_legend(new_loc='upper?left',?bbox_to_anchor=(1.05,?1.0))
ax2.set_title("ax2")

ax12?=?ax1|ax2
ax12.savefig("ax12.png")

#省略 ax1、ax2、ax4绘制过程ax124 = ax1|ax2|ax4
ax124.savefig("../img/ax124.png")

#省略 ax124、ax3、ax5绘制过程
ax12435 = ax124/(ax3|ax5)
ax12435.savefig("../img/ax12435.png")

【案例3-结合plotnine】在plotnine中使用patchworklib拼图

此处主要使用pw.load_ggplot方法。关于plotnine👉plotnine!!!终于可以在Python中使用ggplot2

import?patchworklib?as?pw?
from?plotnine?import?*?
from?plotnine.data?import?*??g1?=?(ggplot(mtcars)?+?geom_point(aes("mpg",?"disp")))?
g1?=?pw.load_ggplot(g1,?figsize=(2,3))?#每个子图重复使用pw.load_ggplot方法g2?=?(ggplot(mtcars)?+?geom_boxplot(aes("gear",?"disp",?group="gear")))?
g2?=?pw.load_ggplot(g2,?figsize=(2,3))g3?=?(ggplot(mtcars,?aes('wt',?'mpg',?color='factor(gear)'))?+?geom_point()?+?stat_smooth(method='lm')?+?facet_wrap('~gear'))?
g3?=?pw.load_ggplot(g3,?figsize=(3,3))g4?=?(ggplot(data=diamonds)?+?geom_bar(mapping=aes(x="cut",?fill="clarity"),?position="dodge"))??
g4?=?pw.load_ggplot(g4,?figsize=(5,2))#拼图
g1234?=?(g1|g2|g3)/g4?
g1234.savefig()

d28ceeffa15ad2a35471309c288b0f29.png

【参考资料】Patchworklib官网: https://github.com/ponnhide/patchworklib

【发文章不易,请多多关注、点赞、下载支持!谢谢!】

文章来源:https://blog.csdn.net/cdl3/article/details/135179878
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。