在Python with loop中用数字绘制多个圆(返回空白数字)

2024-04-19 05:51:19 发布

您现在位置:Python中文网/ 问答频道 /正文

类似于this问题,但适用于许多带有数字的圆。我不知道为什么,但是生成的数字是空白的。我想一个数字与9个圆圈(有3种颜色之一),与“工作标识”打印在圆。你知道吗

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()

Tags: importidasjobplt数字lightbluecolor
2条回答

你需要在0-1范围内绘制x-y坐标。为此,我将x和y除以数据帧中的最大值。稍后,我相应地调整x和y限制,并标记轴以显示实际值。你知道吗

你的字典里也只有两个'green',但有四个'lightblue'。我纠正了。我还将indexbb替换为row['job_id'],因为索引以0开头,但您希望在x=1处绘制圆1

for index, row in df.iterrows():
    ax.text(row['job_id']/max(d['job_id']),row['alerts']/max(d['alerts']),str(row['job_id']), 
            bbox={"boxstyle" : "circle", "color":row['color']})

plt.xlim(0, 1.1)    
plt.ylim(0, 1.1) 
plt.xticks(np.linspace(0,1,10), range(10))
plt.yticks(np.linspace(0,1,10), range(0,50,5))

enter image description here

两个问题。你知道吗

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

enter image description here

相关问题 更多 >