首页 > 解决方案 > 使用循环在 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()

标签: pythonmatplotlib

解决方案


两个问题。

  • 变换设置为图形变换。这将在两个方向上取 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()

在此处输入图像描述


推荐阅读