python - 使用循环在 Python 中绘制多个带有数字的圆圈(返回空白图)
问题描述
与此问题类似,但对于许多带有数字的圆圈。我不知道为什么,但生成的数字是空白的。我想要一个有 9 个圆圈(有 3 种颜色中的一种)的图形,圆圈中印有“job_id”。
import matplotlib.pyplot as plt
import pandas as pd
d = {'job_id': [1, 2, 3, 4, 5, 6, 7, 8, 9],
'hub': ['ZH1', 'ZH1', 'ZH1', 'ZH2', 'ZH2', 'ZH3', 'ZH3', 'ZH3', 'ZH3'],
'alerts': [18, 35, 45, 8, 22, 34, 29, 20, 30],
'color': ['orange', 'orange', 'orange', 'green', 'green', 'lightblue', 'lightblue', 'lightblue', 'lightblue']}
df=pd.DataFrame(data=d)
ax=plt.subplot(111)
for index, row in df.iterrows():
print(row)
ax.text(index,row['alerts'],str(row['job_id']), transform=plt.gcf().transFigure,
bbox={"boxstyle" : "circle", "color":row['color']})
plt.show()
解决方案
两个问题。
- 变换设置为图形变换。这将在两个方向上取 0 到 1 之间的数字。但是,您的数据范围远高于 1。由于您似乎无论如何都想在数据坐标中显示圆圈,请删除该
transform=...
部分。 - 文本元素不能用于自动缩放轴。因此,您需要手动设置限制。
完整代码:
import matplotlib.pyplot as plt
import pandas as pd
d = {'job_id': [1, 2, 3, 4, 5, 6, 7, 8, 9],
'hub': ['ZH1', 'ZH1', 'ZH1', 'ZH2', 'ZH2', 'ZH3', 'ZH3', 'ZH3', 'ZH3'],
'alerts': [18, 35, 45, 8, 22, 34, 29, 20, 30],
'color': ['orange', 'orange', 'orange', 'green', 'green', 'lightblue', 'lightblue', 'lightblue', 'lightblue']}
df=pd.DataFrame(data=d)
ax=plt.subplot(111)
for index, row in df.iterrows():
ax.text(index, row['alerts'],str(row['job_id']),
bbox={"boxstyle" : "circle", "color":row['color']})
ax.set(xlim=(-1,len(df)), ylim=(df["alerts"].min()-5, df["alerts"].max()+5))
plt.show()
推荐阅读
- python - 如果我不知道主题的数量,我可以使用 LDA 主题建模吗
- spring-mvc - 未经授权:令牌丢失
- java - 为什么 JSON 的值在 Helper 类中将“:”更改为“=”
- handlebars.js - 避免将变量应用于嵌套的 Handlebars 部分块
- javascript - 如何在产品上设置多个倒计时?
- database-design - 如何组织客户端数据库 SQL
- apache-kafka - Kafka Orderering Services 如何创建区块?
- excel - 无法以读/写模式打开工作簿
- angular - 在 Electron 中关闭 MatDialogRef
- c# - 将 Delphi 扩展为 C#