单词作为pyplot/matplotlib中的y值

Chm*_*mod 1 python matplotlib

我正在尝试学习如何使用pylab(以及其他工具).我目前正在尝试理解pyplot,但我需要创建一种非常特殊的情节.它基本上是在y轴上用单词而不是数字的线图.

像这样的东西:

hello |   +---+
world |         +---------+ 
      +---|---|---|---|---|-->
      0   1   2   3   4   5
Run Code Online (Sandbox Code Playgroud)

我如何使用任何python图形库?如果你告诉我如何使用pyplot或pylab套件库,可以获得奖励积分.

谢谢!CHMOD

Vik*_*kez 5

我在代码中添加了所有解释:

# Import the things you need
import numpy as np
import matplotlib.pyplot as plt

# Create a matplotlib figure
fig, ax = plt.subplots()

# Create values for the x axis from -pi to pi
x = np.linspace(-np.pi, np.pi, 100)

# Calculate the values on the y axis (just a raised sin function)
y = np.sin(x) + 1

# Plot it
ax.plot(x, y)

# Select the numeric values on the y-axis where you would
# you like your labels to be placed
ax.set_yticks([0, 0.5, 1, 1.5, 2])

# Set your label values (string). Number of label values
# sould be the same as the number of ticks you created in
# the previous step. See @nordev's comment
ax.set_yticklabels(['foo', 'bar', 'baz', 'boo', 'bam'])
Run Code Online (Sandbox Code Playgroud)

而已...

在此输入图像描述

或者,如果您不需要子图:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-np.pi, np.pi, 100)
y = np.sin(x) + 1
plt.plot(x, y)
plt.yticks([0, 0.5, 1, 1.5, 2], ['foo', 'bar', 'baz', 'boo', 'bam'])
Run Code Online (Sandbox Code Playgroud)

如果您不需要图形和子图,这只是做同样事情的较短版本.

  • 在代码的最后一条评论中,您并不完全"正确"; 滴答标签的数量不能与滴答的数量相同.如果tick标签的数量低于ticks的数量,则没有相应的ticklabel的ticks不会得到他们的ticklabel设置并且它仍然是空字符串.如果tick标签的数量高于ticks的数量,则忽略冗余的ticklabel.也不会引发错误.虽然,我认为,对于大多数用途,您的解决方案是最直观的. (2认同)