Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the stemlines color to match the marker color in a stem plot?

Tags:

matplotlib

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: stem lines don't match markers

I want the stem lines to match the color of the markers (blue for the first dataset, green for the second).

like image 647
RubenLaguna Avatar asked Aug 16 '16 21:08

RubenLaguna


2 Answers

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:

stem lines match the marker

like image 74
RubenLaguna Avatar answered Sep 20 '22 18:09

RubenLaguna


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()

enter image description here

like image 26
Mr Fooz Avatar answered Sep 17 '22 18:09

Mr Fooz