简体   繁体   English

在python中在图形上创建框

[英]create boxes on graph in python

I want this kind of result .我想要这样的结果 I want my code to read elements of a text file and if element=='healthy' it should create a box in a graph and its color should be green ('healthy written in box').我希望我的代码读取文本文件的element=='healthy' ,如果element=='healthy'它应该在图形中创建一个框并且它的颜色应该是绿色('healthy write in box')。 else if element=='unhealthy' it should create a box and its color should be red (with 'unhealthy written in box').否则,如果element=='unhealthy'它应该创建一个盒子并且它的颜色应该是红色(带有“不健康写在盒子里”)。 boxes should be horizontally aligned, and if more than 5 then remaining should start from the next row.框应该水平对齐,如果超过 5 个,那么剩余的应该从下一行开始。 (every row should contain only 5 boxes or less). (每行应仅包含 5 个或更少的框)。 The end result should display a graph that contains boxes, red denoting 'unhealthy' and green denoting 'healthy'最终结果应显示一个包含框的图形,红色表示“不健康”,绿色表示“健康”

I found the following code, but it is not working they way I want it to.我找到了以下代码,但它没有按照我想要的方式工作。

import matplotlib.pyplot as plt



plt.style.use('seaborn-white')
import numpy as np
from matplotlib import colors


#open text file (percen) that contains healthy/unhealthy
with open('percen.txt', 'r') as f:   
    result= [int(line) for line in f]


data = np.random.rand(10,10) * 20

cmap = colors.ListedColormap(['green'])

cmap1 = colors.ListedColormap(['red'])

bounds = [0,10,20]
norm = colors.BoundaryNorm(bounds, cmap.N)

fig, ax = plt.subplots(2,5 , sharex='col', sharey='row')


for i in range(2):

    for j in range(5):
        for element in result:
            if (element=='healthy'):
                ax[i,j].text(1, -3, 'healthy',
                  fontsize=15, ha='center', color='green')
                ax[i,j].imshow(data,cmap=cmap, norm=norm)
            else:
                ax[i,j].text(1, -3, 'unhealthy',
                 fontsize=15, ha='center', color='red')
                ax[i,j].imshow(data,cmap=cmap1,norm=norm)

fig
plt.show()

There are a few different ways you can do this and your code is probably not the best but we can use it as a starting point.有几种不同的方法可以做到这一点,您的代码可能不是最好的,但我们可以将其用作起点。 Your issue is that you are looping through the plots and then looping through your data again for each plot.您的问题是您正在遍历图,然后为每个图再次遍历数据。 Your current code also adds text above the plot.您当前的代码还在绘图上方添加文本。 If you want the text above I would recommend adding the label as a title, otherwise when you set your text inside the plot you need to specify the coordinates within the grid.如果您想要上面的文本,我建议添加标签作为标题,否则当您在绘图中设置文本时,您需要指定网格内的坐标。

Below is a modified form of your code, play around with it some more to get what you want.下面是你的代码的修改形式,多玩一些以获得你想要的。

import matplotlib.pyplot as plt

plt.style.use('seaborn-white')
import numpy as np
from matplotlib import colors


result = ['healthy', 'unhealthy', 'healthy', 'unhealthy', 'healthy', 'unhealthy', 'healthy', 'healthy', 'unhealthy', 'unhealthy']

data = np.random.rand(10,10) * 20

cmap = colors.ListedColormap(['green'])

cmap1 = colors.ListedColormap(['red'])

bounds = [0,10,20]
norm = colors.BoundaryNorm(bounds, cmap.N)

fig, ax = plt.subplots(2,5 , sharex='col', sharey='row',figsize=(15,8)) # Added figsize to better show your plot



element_index = 0
for i in range(2):

    for j in range(5):
        element = result[element_index] #Instead of the for loop, get the corresponding element

        if (element=='healthy'):
            ax[i,j].text(4.5,4.5, 'healthy',fontsize=15, ha='center' ,color='black',zorder=100) #Change zorder so label is over plot
            ax[i,j].imshow(data,cmap=cmap, norm=norm)
            ax[i,j].set_yticklabels('') #To remove arbitrary numbers on y axis
            ax[i,j].set_xticklabels('') #To remove arbitrary numbers on y axis


        elif element == 'unhealthy':
            ax[i,j].text(4.5,4.5, 'unhealthy',fontsize=15, ha='center' ,color='black',zorder=100)
            ax[i,j].imshow(data,cmap=cmap1,norm=norm)
            ax[i,j].set_yticklabels('') #To remove arbitrary numbers on y axis
            ax[i,j].set_xticklabels('') #To remove arbitrary numbers on x axis



        element_index+=1       #Add 1 to the index so we get the next value for the next plot

fig
plt.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM