【问题标题】:words as y-values in pyplot/matplotlib [duplicate]在 pyplot/matplotlib 中作为 y 值的单词 [重复]
【发布时间】:2013-08-18 21:25:00
【问题描述】:

我正在尝试学习如何使用 pylab(以及它的其他工具)。我目前正在尝试了解 pyplot,但我需要创建一种非常具体的绘图类型。它基本上是一个带有单词而不是 y 轴上的数字的线图。

类似这样的:

hello |   +---+
world |         +---------+ 
      +---|---|---|---|---|-->
      0   1   2   3   4   5

我将如何使用任何 python 图形库来做到这一点?如果您向我展示如何使用 pyplot 或 pylab 套件库,将获得奖励积分。

谢谢! 修改

【问题讨论】:

标签: python matplotlib


【解决方案1】:

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

# 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'])

就是这样……

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

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'])

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

【讨论】:

  • 在您代码的最后一条评论中,您并不完全“正确”;刻度标签的数量不必必须与刻度的数量相同。如果刻度标签的数量小于刻度的数量,则没有相应刻度标签的刻度不会得到它们的刻度标签,它仍然是一个空字符串。如果刻度标签的数量大于刻度的数量,则忽略多余的刻度标签。两者都不会引发错误。虽然,我同意您的解决方案在大多数情况下是最直观的。
  • 非常简洁的答案,这正是我想要的!非常感谢大家!
猜你喜欢
  • 1970-01-01
  • 2011-07-27
  • 2017-12-12
  • 1970-01-01
  • 2018-06-12
  • 2022-12-21
  • 1970-01-01
  • 2018-06-19
相关资源
最近更新 更多