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.
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:
If you leave out the color
keyword, autocolouring will be used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With