0

I'd like to modify the axis of a stem plot, e.g. to change the grid color with ax.grid(color='gray', axis='y') in the stem plot example. How would I do that?

import matplotlib.pyplot as plt
import numpy as np

# returns 10 evenly spaced samples from 0.1 to 2*PI
x = np.linspace(0.1, 2 * np.pi, 10)

markerline, stemlines, baseline = plt.stem(x, np.cos(x), '-.')

# setting property of baseline with color red and linewidth 2
plt.setp(baseline, color='r', linewidth=2)

stem plot

Max Ghenis
  • 14,783
  • 16
  • 84
  • 132
  • 1
    All plotting functions in matplotlib return an artist or tuple of artists. The only pyplot functions that return an axes are those that also create an axes, `plt.subplots()`, `plt.subplot`, `plt.axes()`, and `plt.gca()`. Here `ax = plt.gca()` can be used. In that sense it's probably a duplicate of [How to get a matplotlib Axes instance to plot to?](https://stackoverflow.com/questions/15067668/how-to-get-a-matplotlib-axes-instance-to-plot-to)? – ImportanceOfBeingErnest Apr 17 '19 at 11:47
  • Thanks, I revised my question. I was mistaken as I typically use `pandas` plotting, which returns an axis but doesn't make stem plots available. – Max Ghenis Apr 17 '19 at 16:33
  • @Sheldore thanks for the reminder, and for your answer which I accepted. I am not new to SO. – Max Ghenis Jun 05 '19 at 23:34

3 Answers3

1

Alternatively, you can just use plt without defining ax. Although I prefer the latter (your answer).

plt.grid(color='gray', axis='y')

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71
0

First define the axis using plt.subplots(), then call as ax.stem rather than plt.stem:

fig, ax = plt.subplots()
markerline, stemlines, baseline = ax.stem(x, np.cos(x), '-.')
ax.grid(color='gray', axis='y')

stem plot with gridlines

Max Ghenis
  • 14,783
  • 16
  • 84
  • 132
0

Per How to get a matplotlib Axes instance to plot to?, another option is adding this at the end:

ax = plt.gca()
ax.grid(color='gray', axis='y')

resulting plot

(ht ImportanceOfBeingErnest)

Max Ghenis
  • 14,783
  • 16
  • 84
  • 132