从主干图获取轴

时间:2019-04-17 04:06:56

标签: python matplotlib

我想修改茎图的轴,例如在主干图example中用ax.grid(color='gray', axis='y')更改网格颜色。我该怎么办?

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

3 个答案:

答案 0 :(得分:1)

或者,您可以仅使用plt而不定义ax。尽管我更喜欢后者(您的答案)。

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

enter image description here

答案 1 :(得分:0)

首先使用plt.subplots()定义轴,然后使用ax.stem而不是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

答案 2 :(得分:0)

对于How to get a matplotlib Axes instance to plot to?,另一种选择是在末尾添加:

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

resulting plot

(ht ImportanceOfBeingErnest)