如何在相对简单的 Python 程序中设置 AxesSubplot 的大小?

沃尔夫

Python 3.7 环境

我想创建一个堆叠条形图,在显示为条形的每个子类别的顶部带有一些标签。数据来自CSV文件,有些标签比较长,所以比条宽还大。通过缩放整个图形使条形变得足够大以容纳标签,可以轻松解决该问题,但我无法重新调整整个图的大小。这里的代码:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set()

dataset = 'Number'

dataFrame: pd.DataFrame = pd.read_csv('my_csv_file_with_data.csv', sep=',', header=2)
dataFrame['FaultDuration [h]'] = dataFrame['DurationH']

# ***********************************************************
# Data gymnastics to transform data in desired format
# determine the main categories
mainCategories: pd.Series = dataFrame['MainCategory']
mainCategories = mainCategories.drop_duplicates()
mainCategories = mainCategories.sort_values()
print('Main Categories: '+ mainCategories)

# subcategories
subCategories: pd.Series = pd.Series(data=dataFrame['SubCategorie'].drop_duplicates().sort_values().values)
subCategories = subCategories.sort_values()
print('Sub Categories: '+ subCategories)

# Build new frame with subcategories as headers
columnNames = pd.Series(data=['SubCategory2'])
columnNames = columnNames.append(mainCategories)
rearrangedData: pd.DataFrame = pd.DataFrame(columns=columnNames.values)

for subCategory in subCategories:
    subset: pd.DataFrame = dataFrame.loc[dataFrame['SubCategorie'] == subCategory]
    rearrangedRow = pd.DataFrame(columns=mainCategories.values)
    rearrangedRow = rearrangedRow.append(pd.Series(), ignore_index=True)
    rearrangedRow['SubCategory2'] = subCategory
    for mainCategory in mainCategories:
        rowData: pd.DataFrame = subset.loc[subset['MainCategorie'] == mainCategory]
        if (rowData is not None and rowData.size > 0):
            rearrangedRow[mainCategory] = float(rowData[dataset].values)
        else:
            rearrangedRow[mainCategory] = 0.0

    rearrangedData = rearrangedData.append(rearrangedRow, ignore_index=True)

# *********************************************************************
# here the plot is created:
thePlot = rearrangedData.set_index('SubCategory2').T.plot.bar(stacked=True, width=1, cmap='rainbow')
thePlot.get_legend().remove()

labels = []

# *************************************************************
# creation of bar patches and labels in bar chart
rowIndex = 0
for item in rearrangedData['SubCategory2']:
        colIndex = 0
        for colHead in rearrangedData.columns:
            if colHead != 'SubCategory2':
                if rearrangedData.iloc[rowIndex, colIndex] > 0.0:
                    label = item + '\n' + str(rearrangedData.iloc[rowIndex, colIndex])
                    labels.append(item)
                else:
                    labels.append('')

            colIndex = colIndex + 1
        rowIndex = rowIndex + 1

patches = thePlot.patches

for label, rect in zip(labels, patches):
    width = rect.get_width()
    if width > 0:
        x = rect.get_x()
        y = rect.get_y()
        height = rect.get_height()
        thePlot.text(x + width/2., y + height/2., label, ha='center', va='center', size = 7 )

# Up to here things work like expected...
# *******************************************************
# now I want to produce output in the desired format/size

# things I tried:
1)    thePlot.figure(figsize=(40,10)) <---- Fails with error 'Figure' object is not callable
2)    plt.figure(figsize=(40,10)) <---- Creates a second, empty plot of the right size, but bar chart remains unchanged
3)    plt.figure(num=1, figsize=(40,10)) <---- leaves chart plot unchanged

plt.tight_layout()
plt.show()

对象“thePlot”是一个 AxesSubplot。如何获得适当缩放的图表?

RVA92

您可以使用以英寸为单位的设置尺寸:

theplot.set_size_inches(18.5, 10.5, forward=True)

例如,请参阅:如何更改使用 matplotlib 绘制的图形的大小?

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章