具有绘制子图功能的意外结果

问题描述 投票:0回答:1

我创建了下一个函数来绘制 barplotd,我想使用这个函数来制作子图,但是当我尝试它时,我没有得到我期望的结果:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

def plotsApilate(data,posColInit,posColEnd, tittleComplement, ax=None):
  data['total']=data.iloc[:,posColInit:posColEnd].sum(axis=1)
  data= data.sort_values(by='total', ascending=True).drop('total', axis=1)
  if ax is None:
      # Gráfico de barras apiladas horizontales
      fig, ax = plt.subplots(figsize=(8,9))

  data.set_index('variable')[['negative', 'neutral', 'positiv']].plot(kind='barh', stacked=True, ax=ax )


  # Show tikcs
  for container in ax.containers:
      ax.bar_label(container, label_type='center',fontsize=6)

  plt.title('Kind of Category' + ' ' + tittleComplement)
  plt.xlabel('Quantity')
  plt.ylabel('Variables')
  plt.legend(title='Legend:')
  plt.show()

# EXAMPLE
Categories= ['CAT1', 'CAT2', 'CAT3', 'CAT4', 'CAT5', 'CAT6']
negative1 = np.random.randint(0, 100, 6)
neutral1= np.random.randint(0, 100, 6)
positiv1= np.random.randint(0, 100, 6)
negative2 = np.random.randint(42, 100, 6)
neutral2= np.random.randint(42, 100, 6)
positiv2= np.random.randint(42, 100, 6)

# CreaTE dataframes
data1 = {'variable': Categories, 'negative': negative1, 'positiv': positiv1, 'neutral': neutral1}
df1 = pd.DataFrame(data1)

data2 = {'variable': Categories, 'negative': negative2, 'positiv': positiv2, 'neutral': neutral2}
df2 = pd.DataFrame(data2 )


# Create figure and subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))

# Ploting 1st DF
plotsApilate(df1, 2,4,'XXX', ax1)

# Ploting 2nd DF
plotsApilate(df2, 2,4,'YYY', ax2)

# fix design
plt.tight_layout()

plt.show()

我有下一个结果,代码中的错误是什么?我想要每个 df 一张图。

enter image description here

python matplotlib bar-chart subplot
1个回答
0
投票

当您仅绘制第一个数据集时,函数中对

plt.show
的调用会中断您的示例。这就是为什么你只得到左侧图表的第一个数字。第一个数据集的标题位于错误的子图上,因为您使用
plt.title
等,它使用 active 轴。如果您没有使用 plt.sca 明确设置
active
轴,这将是最近创建的轴。

当您尝试绘制第二个数据集时,您想要的轴位于已关闭的图形上。因此,

plt
函数会创建一个新图形,因此您得到的只是标题、标签和空图例。

所以我的解决方案是

  • 不要在函数内调用
    plt.show()
  • 用轴方法替换标题/标签/图例函数,这样我们就可以确保它们使用正确的轴。

保持示例不变,仅更改功能:

def plotsApilate(data,posColInit,posColEnd, tittleComplement, ax=None):
  data['total']=data.iloc[:,posColInit:posColEnd].sum(axis=1)
  data= data.sort_values(by='total', ascending=True).drop('total', axis=1)
  if ax is None:
      # Gráfico de barras apiladas horizontales
      fig, ax = plt.subplots(figsize=(8,9))

  data.set_index('variable')[['negative', 'neutral', 'positiv']].plot(kind='barh', stacked=True, ax=ax )


  # Show tikcs
  for container in ax.containers:
      ax.bar_label(container, label_type='center',fontsize=6)

  ax.set_title('Kind of Category' + ' ' + tittleComplement)
  ax.set_xlabel('Quantity')
  ax.set_ylabel('Variables')
  ax.legend(title='Legend:')

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.