How can I make the baseline extend to the axis limits instead of ending with the last data points when generating a stem plot with matplotlib?
Asked
Active
Viewed 2,263 times
3
-
Please provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Diziet Asahi Nov 09 '17 at 10:11
1 Answers
2
The baseline of a plt.stem
plot is returned from the function call,
markerline, stemlines, baseline = plt.stem(x, np.cos(x), '-.')
You can set the data of that line to be [0,1]
and use the yaxis_transform
, such that those coordinates are interpreted as axis coordinates.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.1, 2*np.pi, 10)
markerline, stemlines, baseline = plt.stem(x, np.cos(x), '-.')
plt.setp(baseline, 'color', 'r', 'linewidth', 2)
baseline.set_xdata([0,1])
baseline.set_transform(plt.gca().get_yaxis_transform())
plt.show()

ImportanceOfBeingErnest
- 321,279
- 53
- 665
- 712
-
Thank you - this worked well. Sorry for my poor initial post---thanks for cleaning it up. I come from years of MATLAB and have just recently started trying to use Python. How did you figure out this solution? I could not find any documentation about the properties of the baseline handle. – jboss Nov 10 '17 at 15:03
-
You are right, this solution is by far not obvious and you would only know it by having used `get_yaxis_transform()` in other cases already. So in short: experience. The fact that a stem plot returns three objects however is clear from the documentation. Also it usually helps to just look at the return types and read about the returned object in the docs. – ImportanceOfBeingErnest Nov 10 '17 at 15:45