pythonmatplotlibgraphing

Is it possible to change the color of only one dot in a scatter plot in matplotlib?


So this is my code currently,

import random
import statistics
import matplotlib.pyplot as mpl

x = random.randint(1, 100)
i = 0
tries = []
z = 0

while True:
    i+=1
    y = random.randint(1, 100)
    tries.append(y)
    if y==x:
        y=z
        print(f"The computer got it right in {i} tries.")
        print(f"The number was {x}")
        break

print(tries)
mpl.plot(tries, tries, 'o')
mpl.show()

So it's about getting the computer to guess a random number, putting all the attempts in a list, and plotting all the attempts in a scatter plot. So is it possible to change the color of only the correct attempt in the graph, and having the rest all be default?

I tried to store the all the points on the x-axis and y-axis in a numpy array but it changes the color of all of the dots, and not only one dot.


Solution

  • Yes, of course you can.

    To achieve this, you need to handle the plotting of that specific point separately from the others.

    Plotting All Guesses Except the Last One

    mpl.plot(tries[:-1], tries[:-1], 'o', color='blue')
    

    tries[:-1]: This is a slicing operation on the tries list. It selects all elements of the list except the last one

    Plotting the Last Guess with a Different Color

    mpl.plot(tries[-1], tries[-1], 'o', color='red')
    

    tries[-1]: This time, the code uses negative indexing to select only the last element of the tries list.

    Full code:

    import random
    import matplotlib.pyplot as mpl
    
    
    x = random.randint(1, 100)
    i = 0
    tries = []
    
    while True:
        i += 1
        y = random.randint(1, 100)
        tries.append(y)
        if y == x:
            print(f"The computer got it right in {i} tries.")
            print(f"The number was {x}")
            break
    
    # Plot the wrong guesses blue
    mpl.plot(tries[:-1], tries[:-1], 'o', color='blue')
    
    # Plot the right guess in red
    mpl.plot(tries[-1], tries[-1], 'o', color='red')
    
    mpl.show()