Search code examples
pythonfunctionmatplotlibdata-sciencescatter-plot

MatPlotLib Scatter not working Inside Function


I am a beginner in Python. I have been trying my hands on MatPlotLib to compare the stats of soccer players in FIFA 20. Basically the problem I'm facing is:

def make_graph(value1, value2, namevalue, label1, label2):
    print(value1, value2, namevalue)
    plt.scatter(value1, value2)
    plt.xlabel(label1)
    plt.ylabel(label2)
    for i in range(len(namevalue)):
        plt.text(value1[i] + 0.3, value2[i] + 0.3, namevalue[i], fontdict=dict(color='red', size=10), bbox=dict(facecolor = 'yellow', alpha=0.5))

    plt.xlim(min(value1) - 5, max(value2) + 5)
    plt.ylim(min(value1) - 5, max(value2) + 5)
    plt.show()





def Test():

    df = xlrd.open_workbook(path)
    data = df.sheet_by_index(0)

    data.cell_value(0,0)
    name = []
    pace = []
    shoot = []
    for i in range(1, 450):
        #print(data.cell_value(i, 3))
        buff = str(data.cell_value(i,2)).strip()
        if buff == "LM" or buff == "RM":
            pacebuffer = int(data.cell_value(i, 4))
            shootbuffer = int(data.cell_value(i, 5))
            if pacebuffer >= 90:
                name.append(data.cell_value(i, 3).strip("\n"))
                pace.append(pacebuffer)
                shoot.append(shootbuffer)

    #print(name)
    make_graph(pace, shoot, name, "Pace", "Shoot")

The particular code is showing me an empty graph. BUT When I write the same piece of code inside Test() which I wrote inside make_graph() , it gives me the desired output. But in this way I have to rewrite that plotting thing every time I write some other functions and that's really a problem. Any idea how to fix this?


Solution

  • It is your x and y lims :

    plt.xlim(min(value1) - 5, max(value2) + 5)
    plt.ylim(min(value1) - 5, max(value2) + 5)
    

    You should change to :

    plt.xlim(min(value1) - 5, max(value1) + 5)
    plt.ylim(min(value2) - 5, max(value2) + 5)
    

    Technically your plt.scatter was working but then your x and y lims meant that you couldn't see.