8

I need to extract style information of a matplotlib.lines.Line2D object to use it in a matplotlib.pyplot.plot() call. And (if possible) I want to make it in a more elegant way than filtering style-related properties from Line2D.properties() output.

The code may be like that:

import matplotlib.pyplot as plt

def someFunction(a, b, c, d, **kwargs):
    line = plt.plot(a, b, marker='x', **kwargs)[0]
    plt.plot(c, d, marker='o', **kwargs) # the line I need to change

In the case I want to have both lines plotted with the same styles (including colour), but with different marker. Also, I want to be able to use 'autocolouring' feature of the plot() function unless colour has been given explicitly as keyword argument.

1 Answer 1

10

The Line2D object that is returned by plt.plot() has an update_from() method, which copies all attributes from the original instance to the new one, but leaves the data of the line alone. You could use this line to copy all attributes and afterwards set all attributes that should differ 'by hand'. Here a little example:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D


def someFunction(a, b, c, d, *args, **kwargs):
    line1, = plt.plot(a, b, marker='x', *args, **kwargs)
    line2, = plt.plot(c, d) # the line I need to change

    ##copy properties from line1
    line2.update_from(line1)

    ##set every that should differ *after* update_from()
    line2.set_marker('o')


x1 = np.linspace(0,np.pi,10)
x2 = np.linspace(np.pi,2*np.pi,10) 
y1 = -np.sin(x1)**2
y2 = np.sin(x2)**2

someFunction(x1,y1,x2,y2, '--', lw=3, ms=10, color='g')

plt.show()

This gives the following picture:

result of the above code

If you leave out the color keyword, autocolouring will be used.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.