python - 如何在相对简单的 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。如何获得正确比例的图表?
解决方案
您可以使用以英寸为单位的设置尺寸:
theplot.set_size_inches(18.5, 10.5, forward=True)
例如,请参阅: 如何更改使用 matplotlib 绘制的图形的大小?
推荐阅读
- linux - *** 检测到缓冲区溢出 ***: /usr/local/sbin/tincd 终止
- wso2 - WSO2 身份服务器错误生成 API 密钥
- python-sphinx - Sphinx 文档:HTML 文档的自定义图像目录和 _static 目录
- python - drop_duplicates 不适用于多个相同的行实例
- angular - 使用角度 cli 在页眉中放置图像
- asp.net-core - Razor Pages:第二个发布按钮后的持久模型数据
- python - 收到此错误后应该做什么:AttributeError: 'int' object has no attribute 'lower'
- abap - 如何在 LEFT OUTER JOIN 中为选择选项编写条件?
- java - 当我运行我的迷你 spring-boot 项目时,为什么关闭了与 mongodb 的连接?
- java - 可以将 Java Jax-ws 应用程序转换为 rest 吗?