Reputation: 3243
I need to generate a graph using matplotlib like the one in the attached picture. So far I tried it like this:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([0,1,2,3])
y = np.array([20,21,22,23])
my_xticks = ['John','Arnold','Mavis','Matt']
plt.xticks(x, my_xticks)
plt.plot(x, y)
plt.show()
How can I specify a different number of values on the y axis different from the number of values on the x axis? And maybe specify them as an interval with 0.005 difference instead of a list?
Upvotes: 44
Views: 168422
Reputation: 23131
The values on y-axis are called y tick labels (ticks are the short lines on an axis). As @Martini showed, it can be set using the state machine. There's also the the object-oriented approach, which I think is more transparent.
This approach is one where you can explicitly create an Axes object and call the appropriate methods (which is done under the hood with plt.xticks()
anyway).
Option #1. For example, to set yticks, there's the dedicated ax.set_yticks()
method.
x = np.array([0,1,2,3])
y = np.array([0.650, 0.660, 0.675, 0.685])
my_xticks = ['John','Arnold','Mavis','Matt']
fig, ax = plt.subplots(facecolor='white') # create figure and axes objects
ax.plot(x, y) # make plot
ax.set_xticks(x) # set x tick positions
ax.set_xticklabels(my_xticks) # set the corresponding x tick labels
ax.set_yticks(np.arange(y.min(), y.max(), 0.005)) # set y tick positions
ax.grid(axis='y'); # draw grid
Option #2. The Axes object also define set()
method that can be used to set multiple properties such as xticks, yticks, ylabel etc.
fig, ax = plt.subplots(facecolor='white')
ax.plot(x, y)
ax.set(xticks=x, xticklabels=my_xticks, yticks=np.arange(y.min(), y.max(), 0.005), xlabel='x axis', ylabel='y axis');
ax.grid(axis='y');
Option #3. Each Axes defines Axis objects as well (YAxis and XAxis), each of which define a set()
method that can be used to set properties on that axis.
fig, ax = plt.subplots(facecolor='white')
ax.plot(x, y)
ax.xaxis.set(ticks=x, ticklabels=my_xticks, label_text='x axis')
ax.yaxis.set(ticks=np.arange(y.min(), y.max(), 0.005), label_text='y axis')
ax.yaxis.grid();
Upvotes: 1
Reputation: 13539
import matplotlib.pyplot as plt
import numpy as np
x = np.array([0,1,2,3])
y = np.array([0.650, 0.660, 0.675, 0.685])
my_xticks = ['a', 'b', 'c', 'd']
plt.xticks(x, my_xticks)
plt.yticks(np.arange(y.min(), y.max(), 0.005))
plt.plot(x, y)
plt.grid(axis='y', linestyle='-')
plt.show()
Something like this should work.
Upvotes: 62