在为循环生成的一个图上绘制多个图形

发布于 2025-02-09 08:29:41 字数 595 浏览 4 评论 0原文

我有一个数据帧字典,并且正在使用以下代码为dict中的每个数据框架生成堆叠的条形图。该代码按预期打印每个堆叠的条形图(每个图表都在笔记本中彼此之间,在笔记本中彼此之间),但我希望它在一个图上打印每个图表,例如,可以说4行带有3列。

for i, key in enumerate(d):
    plt.rcParams["figure.figsize"] = (5,3)
    d[key].plot(kind = 'barh', width= 0.85, stacked = True, color = ['limegreen','gold', 'orange', 'red'])
    plt.legend(bbox_to_anchor = (1.05, 1.025), title = "Categories")
    plt.xlabel('Cumulative Percent')
    plt.gca().xaxis.set_major_formatter(mtick.PercentFormatter())
    plt.ylabel('Data Stream')
    plt.gca().invert_yaxis()
    plt.title(f'{key}')    
plt.show()

I have a dictionary of data frames and I am using the below code to generate a stacked bar chart for every data frame within the dict. The code prints every stacked bar chart as intended (each graph one after the other and below each other in notebook), but I want it to print each chart on one figure, lets say 4 rows with 3 columns for example.

for i, key in enumerate(d):
    plt.rcParams["figure.figsize"] = (5,3)
    d[key].plot(kind = 'barh', width= 0.85, stacked = True, color = ['limegreen','gold', 'orange', 'red'])
    plt.legend(bbox_to_anchor = (1.05, 1.025), title = "Categories")
    plt.xlabel('Cumulative Percent')
    plt.gca().xaxis.set_major_formatter(mtick.PercentFormatter())
    plt.ylabel('Data Stream')
    plt.gca().invert_yaxis()
    plt.title(f'{key}')    
plt.show()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花心好男孩 2025-02-16 08:29:41

使用子图:

# sample data
df = pd.DataFrame(
    {f"col_{i}": np.random.randint(0,100, 50) for i in range(12)}
)


fig, axs = plt.subplots(4, 3, figsize=(25,20))
all_axs = axs.ravel()
for i, c in enumerate(df.columns):    
  ax = df[c].plot(kind = 'barh', 
                  width= 0.85, 
                  stacked = True, 
                  color = ['limegreen','gold', 'orange', 'red'], 
                  ax=all_axs[i])
  ax.legend(title = "Categories")
  ax.set_xlabel("Cumulative Percent")
  ax.set_ylabel("Data Stream")
  ax.xaxis.set_major_formatter(mtick.PercentFormatter())
  ax.invert_yaxis()

fig.tight_layout()

输出:

using subplots:

# sample data
df = pd.DataFrame(
    {f"col_{i}": np.random.randint(0,100, 50) for i in range(12)}
)


fig, axs = plt.subplots(4, 3, figsize=(25,20))
all_axs = axs.ravel()
for i, c in enumerate(df.columns):    
  ax = df[c].plot(kind = 'barh', 
                  width= 0.85, 
                  stacked = True, 
                  color = ['limegreen','gold', 'orange', 'red'], 
                  ax=all_axs[i])
  ax.legend(title = "Categories")
  ax.set_xlabel("Cumulative Percent")
  ax.set_ylabel("Data Stream")
  ax.xaxis.set_major_formatter(mtick.PercentFormatter())
  ax.invert_yaxis()

fig.tight_layout()

output:
enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文