1

I am trying to learn how to use pylab (along with the rest of its tools). I'm currently trying to understand pyplot, but I need to create a very specific type of plot. It's basically a line plot with words instead of numbers on the y-axis.

Something like this:

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

How would I do that with any python graphic library? Bonus points if you show me how to with pyplot or pylab suite libraries.

Thanks! Chmod

joaquin
  • 82,968
  • 29
  • 138
  • 152
Chmod
  • 107
  • 1
  • 9

1 Answers1

5

I added all the explanations into the code:

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

Thats it...

enter image description here

Or if you don't need the subplots just:

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

This is just a shorter version of doing the same thing if you don't need a figure and subplots.

Viktor Kerkez
  • 45,070
  • 12
  • 104
  • 85
  • 2
    In the last comment in your code, you are not entirely "correct"; the number of ticklabels does not _have to be_ the same as the number of ticks. If the number of ticklabels is lower than the number of ticks, the ticks without a corresponding ticklabel doesn't get their ticklabel set and it remains an empty string. If the number of ticklabels is higher than the number of ticks, the redundant ticklabels are ignored. Neither will raise an error. Although, I agrre that for most purposes your solution is the most intuitive. – sodd Aug 17 '13 at 11:55
  • Very concise answer, and it was exactly what I was looking for! Thank you very much to everyone! – Chmod Aug 19 '13 at 14:14