python - 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:
# 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:
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
解决方案
这是plt.figure(constrained_layout=True)
应该做的。如果你想进一步拉伸它,你可以这样做:
width, height = plt.rcParams.get('figure.figsize')
plt.figure(constrained_layout=True, figsize=(len(sports_name)/3, height))
推荐阅读
- python - 没有使用scrapy的内部方法调用
- mysql - 我不明白 Laravel 中的功能(Builder $query)是如何工作的
- c# - 滚动数据网格
- db2 - 使用 DB2 检索不区分大小写的 SQL 选择查询
- c# - 我无法在 Raspberry Pi 上使用 Monodevelop 构建 C# 代码
- javascript - 如何从 df ~ 提取数据到我的网站上?
- angular - 如何以角度格式化来自数据库的日期
- node.js - 如何使用 nodeJS 通过 Aws Lambda 评级对数据进行排序
- php - 使用 MySQLi 的动态表名和准备好的语句
- c# - 在终结器中使用(反应式)事件