python - 如何在循环中为seaborn图表执行子图
问题描述
我有生成四个子图的代码,但我想通过循环生成这些图表,目前我正在按照这段代码生成图表代码:
plt.figure(figsize=(20, 12))
plt.subplot(221)
sns.barplot(x = 'Category', y = 'POG_Added', data = df)
xticks(rotation = 90)
plt.xticks(size = 11)
plt.yticks(size = 11)
plt.xlabel("Category",size = 13)
plt.ylabel("POG_Added",size = 13)
plt.subplot(222)
sns.barplot(x = 'Category', y = 'Live_POG', data = df)
xticks(rotation = 90)
plt.xticks(size = 11)
plt.yticks(size = 11)
plt.xlabel("Category",size = 13)
plt.ylabel("Live_POG",size = 13)
plt.subplot(223)
sns.lineplot(x = 'Category', y = 'D01_CVR', data = df)
#sns.barplot(x = 'Category', y = 'D2-08-Visits', data = df,label='D2-08_Visits')
xticks(rotation = 90)
plt.xticks(size = 11)
plt.yticks(size = 11)
plt.xlabel("Category",size = 13)
plt.ylabel("D01_CVR",size = 13)
plt.subplot(224)
plt.xticks(rotation='vertical')
ax = sns.barplot(x='Category',y='D2-08-Units',data=df)
ax2 = ax.twinx()
ax2.plot(ax.get_xticks(), df["D01_CVR"], alpha = .75, color = 'r')
plt.subplots_adjust(hspace=0.55,wspace=0.55)
plt.show()
解决方案
以下是我如何做这样的事情:
import numpy as np
import matplotlib.pyplot as plt
data = [np.random.random((10, 10)) for _ in range(6)]
fig, axs = plt.subplots(ncols=3, nrows=2, figsize=(9, 6))
for ax, dat in zip(axs.ravel(), data):
ax.imshow(dat)
这会产生:
这个想法是plt.subplots()
产生一个Axes
对象数组,所以你可以循环它并在循环中制作你的图。在这种情况下,我需要ndarray.ravel()
因为axs
是一个二维数组。
推荐阅读
- apache - 将子域重写为 Apache .htaccess 文件中的子目录
- swift - 以编程方式呈现 SwiftUI 视图不起作用
- android-10.0 - 如何在android Q(10)中解决Environment.getExternalStorageDirectory()
- spring-boot - 如何确定在控制器方法中选择了 @RequestMapping 注释的哪种映射?
- java - 从证书的给定公钥生成 AsymmetricCipherKeyPair 椭圆曲线
- c# - 如何在 C# 中获取具有其实例的字段名称?
- javascript - Javascript Promises:第 9 位 JSON 中的意外标记 <
- javascript - 复制粘贴时在 Node.js REPL 中处理自动缩进
- c# - 无法在 asp.net core 2.2 中更新会话数据
- docker - Docker 看不到所有磁盘 - 设备上没有剩余空间