user2154227
user2154227

Reputation:

Duplicating the same plot in Python in one figure with separate legends

I wanted to duplicate the same plot on the same figure with different colors and legends and here is my minimalistic working code.

import matplotlib.pyplot as plt
import numpy as np

def make_layout(data):
    fig = plt.figure()

    ax = fig.add_subplot(111)

    p, = ax.plot(data,'o')

    p.set_markerfacecolor('g')
    # Presumably lots of complicated settings here

    return fig, ax, p

data = data = np.linspace(0,1)

f1, a1, p1 = make_layout(data)
f2, a2, p2 = make_layout(data**2)


p2.set_markerfacecolor('yellow')

Here are the two plots i got in separate figures and they don't look like the same. How can i do that? Thank you for any help.

enter image description here

enter image description here

I wanted to merge them in one same figure. I also wanted to add legends and labels.

Upvotes: 2

Views: 90

Answers (1)

Paul H
Paul H

Reputation: 68216

Your plotting function needs to accept an Axes object as a parameter. You then create the figure and axes outside of the function:

import matplotlib.pyplot as plt
import numpy as np

def make_layout(data, ax):
    p, = ax.plot(data, 'o')
    p.set_markerfacecolor('g')
    return p

So to plot everything on 1 Axes, you'd do:

data = data = np.linspace(0,1)
fig, ax = plt.subplots(nrows=1, ncols=1)
p1 = make_layout(data, ax)
p2 = make_layout(data**2, ax)
p2.set_markerfacecolor('yellow')

If you want separate axes, you'd do something like this:

data = data = np.linspace(0,1)
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2)
p1 = make_layout(data, ax1)
p2 = make_layout(data**2, ax2)
p2.set_markerfacecolor('yellow')

Upvotes: 2

Related Questions