python-3.x - 是否可以将“plt.yticks”放在单杠之间?
问题描述
我试图将值放在plt.yticks
条形之间。不幸的是,我不知道该怎么做。有可能吗?,如果可以的话,有人可以给点建议吗?
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
age = np.array(
["0 - 4", "5 - 9", "10 - 14", "15 - 19", "20 - 24", "25 - 29", "30 - 34", "35 - 39",
"40 - 44", "45 - 49", "50 - 54", "55 - 59", "60 - 64", "65 - 69", "70 - 74",
"75 - 79", "80 - 84", "85 - 89", "90 - 94", "95 - 99", "> 100"])
m = np.array(
[1915887, 2100931, 2494484, 2464805, 2361297, 2529633, 2669927, 2754129, 2753282,
2552531, 2211649, 1697221, 1311024, 902675, 722246, 482686, 273915, 108639, 35867,
10965, 1238])
f = np.array(
[1823981, 1980712, 2369795, 2435784, 2330223, 2562964, 2724990, 2860720, 2918730,
2713534, 2376384, 1869867, 1454373, 1030677, 885393, 640698, 388748, 172302, 64170,
19868, 2711])
x = np.arange(age.size)
tick_lab = ['3M', '2M', '1M', '1M', '2M', '3M']
tick_val = [-3000000, -2000000, -1000000, 1000000, 2000000, 3000000]
def plot_pyramid():
plt.barh(x, -m, alpha=.75, height=.75, align='center' , color="deepskyblue")
plt.barh(x, f, alpha=.75, height=.75, align='center', color="pink")
plt.yticks(x, age)
plt.xticks(tick_val, tick_lab)
plt.grid(b=False)
plt.title("Population Pyramid")
plt.show()
if __name__ == '__main__':
plot_pyramid()
解决方案
我只是用plt.barh
下面的行替换了这两行,并plt.title
在函数内部添加了 for 循环并替换ax.set_yticks(False)
为plt.yticks([])
. 我不确定这是否正是您想要的。
# Modified before the function because you are shifting the bars left/right
tick_val = np.array([-3000000, -2000000, -1000000, 1000000, 2000000, 3000000])
shift = 300000
tick_val[0:3] -= shift
tick_val[3:] += shift
# Modified inside the function
plt.barh(x, -m, alpha=.75, height=.75, left=-shift, align='center' , color="deepskyblue")
plt.barh(x, f, alpha=.75, height=.75, left = shift, align='center', color="pink")
for i, j in enumerate(age):
if i==0 or i==1:
plt.text(-150000, x[i]-0.2, j, fontsize=10)
else:
plt.text(-230000, x[i]-0.2, j, fontsize=10)
输出
推荐阅读
- python - 为什么添加用户功能在pyftpdlib中不起作用
- excel - 带有 Google-directions API 的 Excel 网络服务公式
- node.js - Google Tail 日志条目:关于数据事件未收到任何消息
- java - 路径中有空格时找不到持久性提供程序
- python - 如何使用 pydantic/fastapi 接受具有数组\单个项目的单个路由对象?
- python - 没有为 cv-bridge python 找到匹配的分布
- netlogo - 是否可以在 NetLogo 6.2 中将 4 列表转换为 4 列表?
- python - 扩展 layout.html 不适用于我创建的网页之一
- flutter - 提升按钮颜色的颤振小部件测试
- mysql - MYSQL - 拥有多个包含 FK 的列是否是一个好的模式,其中一个必须设置