age_group = ['0~4 years', '5~9 years', '10~14 years', '15~19 years', '20~24 years', '25~29 years', '30~34 years', '35~39 years', '40~44 years', '45~49 years', '50~54 years', '55~59 years', '60~64 years', '65~69 years', '70~74 years', '75~79 years', '80~84 years', '85~89 years', '90~94 years', '95~99 years', '100 and over']
male = [805852, 1133426, 1186319, 1198911, 1681183, 1954718, 1759768, 1877724, 2038116, 2100431, 2243979, 2064943, 2016321, 1433783, 975415, 685723, 447622, 189457, 47148, 8149, 1056]
female = [764557, 1078946, 1118371, 1114388, 1542471, 1708409, 1572504, 1744623, 1943594, 2033792, 2233654, 2032973, 2081537, 1542824, 1114229, 898881, 731214, 428224, 161610, 35719, 5507]
# your code here
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
plt.figure(figsize = (20, 12))
female_array = np.array(female)
plt.barh(age_group, male, label = "Male", color = "turquoise")
plt.barh(age_group, -female_array, label = "Female", color = "violet")
plt.xticks([])
plt.tick_params(axis = "y", color = "w")
plt.title("Population of Korea in 2021", fontsize = 25)
for index, value in enumerate(male):
plt.text(value + 25000, index, format(round(value, -3), ",d"))
for index, value in enumerate(female_array):
plt.text(-value - 250000, index, format(round(value, -3), ",d"))
plt.box(False)
plt.legend(fontsize = 13)
我写了上面的代码来复制我附上的同样的图。但是,因为女性指数和y轴的文本太接近了,我想把整个barh图控制得更窄。你能给予我一些代码让我的python图更像图片吗?
1条答案
按热度按时间roqulrg31#
所以你可以通过使用
tick_param
轻松地为你的ylabels填充添加填充。在右边添加填充有点棘手,我通过在右边添加一个空白图来用一种黑客的方式做到这一点。你可以自定义两边的填充,使它看起来像你喜欢的那样:图片:
与您的原始图像比较: