python - 在 matplotlib 中向热图添加辅助 y 标签
问题描述
我正在尝试使用 twinx() 将辅助 y 标签添加到热图中。但是在我设置辅助 y 标签后,主 y 轴、刻度和标签总是偏移。请参阅下面的结果。第二张图片显示了移除辅助轴时的输出。
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# sphinx_gallery_thumbnail_number = 2
vegetables = ["cucumber", "tomato", "lettuce", "asparagus", "potato", "wheat", "barley"]
v2 = ["1", "2", "3", "4", "5", "6", "7"]
farmers = ["Farmer Joe", "Upland Bros.", "Smith Gardening",
"Agrifun", "Organiculture", "BioGoods Ltd.", "Cornylee Corp."]
harvest = np.array([[0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0],
[2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0],
[1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0],
[0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0],
[0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0],
[1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1],
[0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]])
fig, ax1 = plt.subplots()
im = ax1.imshow(harvest)
ax1.set_xticks(np.arange(len(farmers)))
ax1.set_yticks(np.arange(len(vegetables)))
ax1.set_xticklabels(farmers)
ax1.set_yticklabels(vegetables)
ax2 = ax1.twinx()
ax2.set_yticks(np.arange(len(v2)))
ax2.set_yticklabels(v2)
plt.setp(ax1.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor")
for i in range(len(vegetables)):
for j in range(len(farmers)):
text = ax1.text(j, i, harvest[i, j], ha="center", va="center", color="w")
fig.tight_layout()
plt.show()
解决方案
推荐阅读
- docker - Kubernetes:在同一个端口上运行的微服务?
- r - “句子”向量是如何制作的?(创建字符串向量)
- c++ - 如何在 C++20 chrono 中为日期添加天数?
- docker - 尝试在 Fedora Coreos 上使用 docker-compose 运行 docker nginx 映像,13:权限被拒绝
- mysql - MySQL:为什么这两个是错的?(组函数使用无效,使用have()后什么都不选)
- amazon-web-services - 附加到 EC2 的 AWS 角色在用于 statSd 时引发错误
- python - 为什么即使在 SageMaker 中成功执行了生命周期脚本,包也没有更新?
- swiftui - SwiftUI:为什么 UIHostingController(rootView:) 可以传递 nil 值?
- c# - 使用 FluentFTP 从 FTP 同时下载多个文件
- javascript - 使用 JavaScript 获取所有 covid-19 病例