我正在尝试绘制一个seaborn gridplot子图,以便 1. 图形/绘图的每一行都将包含一个尝试绘制的客户端实体的图形。 2. 该行的列将代表同一客户的不同变量的线图。
例如,如果有客户 ABC、XYZ、PQR 具有历史收入趋势和历史支出趋势, 我想绘制
ABC 的收入子图和旁边的支出子图
XYZ 的收入子图和旁边的支出子图
PQRS 的收入子图和旁边的支出子图。
我可以绘制同一变量的子图,但无法在第二列中包含第二个变量。 任何指针都会非常有用。
num_plots = len(clients)
fig,ax=plt.subplots(30,2,figsize=(12,96))
fig.subplots_adjust(hspace=0.4,wspace=0.4)
for x in range(num_plots):
df = dfABC[dfABC['Client'] == clients[x]]
row = x//2
col = x%2
ax_curr = ax[row,col]
sns.lineplot(data=df,x='Year',y='Income',ax=ax_curr).set_title(clients[x])
这将创建一个 30 行 x 2 列的图,每个图仅代表收入。 我怎样才能将费用线图作为第二列?
最佳答案
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Data generation
clients = ['ABC', 'XYZ', 'PQR']
n_points = 1000
dfABC = pd.DataFrame(
{'Client': np.random.choice(clients, size=n_points),
'Year': np.random.choice([2010, 2011, 2012, 2013], size=n_points),
'Income': np.random.exponential(size=n_points)*10,
'Expense': np.random.exponential(size=n_points)})
# Figure generation
clients = list(dfABC['Client'].unique())
n_rows = len(clients)
fig,ax=plt.subplots(n_rows,2,figsize=(12,96))
fig.subplots_adjust(hspace=0.4,wspace=0.4)
for i, client in enumerate(clients):
df = dfABC[dfABC['Client'] == client]
sns.lineplot(data=df,x='Year',y='Income',ax=ax[i, 0]).set_title(client)
sns.lineplot(data=df,x='Year',y='Expense',ax=ax[i, 1]).set_title(client)
关于python - seaborn gridplot/subplots 在同一行 ID 的第一列上显示一个变量,在第二列上显示另一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59692426/