0

I have a list of values, to which I am applying a function. I want to be able to plot the results of each iteration separately on a scatterplot. To complicate things somewhat, the results list is not the same length for each iteration. I've tried playing around with colourmap, but it's not even printing a blank chart.

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
cmap = cm.get_cmap('Set1')

def scatter_plot(list):
    x = []
    y = []
    
    for i in list:
        x.append(i[0])
        y.append(i[1])
        c = cmap(i[2])
    
            plt.figure(figsize=(8,8))
            plt.scatter(x,y, color=c)
            plt.show()

In the function funky_function I have:

return(my_list, a_value)

my_list contains the x and y values for the plot, a_value is the value for which I want each different result a separate colour. The scatter_plot function is picking out the x and y fine for a single value.

To produce the results:

pointlist = funky_function(a_value)
value_list = [1,2,3,4]

for a_value in value_list:
    funky_function(a_value)

scatter_plot(pointlist)

It's printing the results fine, but not plotting them. I want it to be able to just add new results to the plot if I add new items to the value list, hence trying to set the colour to be a dynamic input rather than plot1=color1, plot2=color2.

I had a look at Add colour scale to plot as 3rd variable, but I need the colour to match to a specific item in the list. (I agree with that poster that the info available on colormap isn't very clear.)

Pendragon
  • 119
  • 9
  • pass the lists directly to `plt.scatter` only once and outside of your loop – Paul H Jun 06 '22 at 18:56
  • I lined plt.scatter(x,y, color=c) up with the for clause, and then got an error 'UnboundLocalError: local variable 'c' referenced before assignment' – Pendragon Jun 06 '22 at 19:07
  • I've tried several options, including putting the appended items in plt,scatter, but I'm still not sure what exactly you mean by passing the list directly to the plotting function. – Pendragon Jun 06 '22 at 19:40
  • `plt.scatter(list_x, list_y, color=list_c)`. Look at any of the examples in the Matplotlib docs for more info – Paul H Jun 06 '22 at 19:41
  • Unfortunately all the examples I can find online are either using random numbers or the product of a function, rather than .append. I tried list_x etc, but it complained about it not being defined. – Pendragon Jun 06 '22 at 20:24
  • lists and arrays are lists and arrays. Doesn't matter if you use `.append` or not – Paul H Jun 06 '22 at 21:10

0 Answers0