Draw scatterplots on different plots

Tags: ,



I have a custom function that creates a scatterplot:

def scatterplot(df):
  
 enrich,number=separate_types(df) 
 fig=plt.figure(1)
 axes=plt.gca()

 plt.xlabel("P")
 plt.ylabel("E")
 for i in range(len(enrich)):
    if enrich["Treatment"][i]=="C":
        color="tab:blue"
    else:
        color="tab:orange"
    plt.errorbar(x=number["mean"][i],y=enrich["mean"][i],yerr=enrich["stdev"][i],xerr=number["stdev"][i],color=color,marker=".",label=enrich["Treatment"][i])

handles, labels = plt.gca().get_legend_handles_labels()
by_label = dict(zip(labels, handles))
plt.legend(by_label.values(), by_label.keys())
return(fig)

The idea is to get a scatterplot that has x errors and y errors on it, as well as a color scheme based on a different column.

I’ve noticed that if I were to do use d1 (of 5 points total) like this:

scatterplot(d1)

And then another d2 (of 5 points total) like this:

scatterplot(d2)

I’d get 1 plot with 10 points. I want 2 plots with 5 points (each belonging to d1 and d2). How do I modify the function to accomodate this?

Answer

The documentation highlights why this behavior happens.

By calling fig=plt.figure(1) you create a new figure if there is no other figure with the same identifier. In your case, this means the 1. In your case, the figure with the identifier with the 1 is always restored and no new figure is created.

https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.figure.html#matplotlib.pyplot.figure

From the documentation:

num: int or str or Figure, optional

A unique identifier for the figure.

If a figure with that identifier already exists, 
this figure is made active and returned. An integer 
refers to the Figure.number attribute, a string refers to 
the figure label.


Source: stackoverflow