Stem lines are always blue:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.1, 2*np.pi, 10)
plt.stem(x, np.sin(x), markerfmt='o', label='sin')
plt.stem(x+0.05, np.cos(x), markerfmt='o', label='cos')
plt.legend()
plt.show()
produce:
I want the stem lines to match the color of the markers (blue for the first dataset, green for the second).
One way of solving this is to modify the stem lines after the call to plt.stem
. We can obtain the color of the marker using plt.getp(..., 'color')
and use plt.setp
to assign that color to the stem lines:
x = np.linspace(0.1, 2*np.pi, 10)
markerline, stemlines, baseline = plt.stem(x, np.sin(x), markerfmt='o', label='sin')
plt.setp(stemlines, 'color', plt.getp(markerline,'color'))
plt.setp(stemlines, 'linestyle', 'dotted')
markerline, stemlines, baseline = plt.stem(x+0.05, np.cos(x), markerfmt='o', label='cos')
plt.setp(stemlines, 'color', plt.getp(markerline,'color'))
plt.setp(stemlines, 'linestyle', 'dotted')
plt.legend()
plt.show()
produces:
You can add a formatting argument for each stem as you'd do for plot
. Note the 'b'
and 'g'
arguments in the plt.stem
calls below.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.1, 2*np.pi, 10)
# v---------- add these args
plt.stem(x, np.sin(x), 'b', markerfmt='bo', label='sin')
plt.stem(x+0.05, np.cos(x), 'g', markerfmt='go', label='cos')
plt.legend()
plt.show()
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