首页 > 解决方案 > Calculate figsize automatically in matplotlib

问题描述

While trying to find a good answer for my on google I stumbled on this:
https://www.pythonpool.com/matplotlib-figsize/
It showed and solved my problem perfectly - from this:
bad_bar_chart

# import the pyplot submodule of matplotlib library
# and rename it as plt
import matplotlib.pyplot as plt
 
# name of the sports
sports_name=['Aquatics', 'Athletics', 'Rowing', 'Gymnastics', 'Fencing', 'Football','Hockey', 'Wrestling', 'Shooting', 'Sailing', 'Cycling','Canoe / Kayak', 'Basketball', 'Volleyball', 'Equestrian', 'Handball','Boxing', 'Weightlifting', 'Judo', 'Baseball', 'Archery', 'Tennis','Rugby', 'Softball', 'Modern Pentathlon', 'Table Tennis', 'Badminton','Tug of War', 'Taekwondo', 'Polo', 'Lacrosse', 'Golf', 'Ice Hockey','Skating', 'Cricket', 'Triathlon', 'Rackets', 'Croquet','Water Motorsports', 'Basque Pelota', 'Jeu de paume', 'Roque']
 
# These are people which play the respective sport
people_playing_the_sports=[3828, 3448, 2523, 2214, 1547, 1387, 1325,140,105,1061,1025,1002,940,910,894,886,842,548,435,335,305,272,192,180,174,120,120,94,80,66,59,30,27,27,24,18,10,8,5,4,3,3]
 
# To create a bar graph use bar function of pyplot
plt.bar(sports_name,people_playing_the_sports)
# Rotate the name of sports by 90 degree in x-axis
plt.xticks(rotation=90)
# show the graph 
plt.show()

To this:
good_bar_chart
Then I looked at their solution...and it just made me wanna... - I got really mad xD
Because they just hardcoded the new width:

plt.figure(figsize=(15,4))

Does anyone know a good way of solving such size issues for any graph, without having to magically come up with the ideal figsize like they seem to suggest? :D

标签: pythonmatplotlib

解决方案


这是plt.figure(constrained_layout=True)应该做的。如果你想进一步拉伸它,你可以这样做:

width, height = plt.rcParams.get('figure.figsize')
plt.figure(constrained_layout=True, figsize=(len(sports_name)/3, height))

推荐阅读