Question
I'm plotting a histogram using the matplotlib.pyplot module and I am wondering how I can force the y-axis labels to only show integers (e.g. 0, 1, 2, 3 etc.) and not decimals (e.g. 0., 0.5, 1., 1.5, 2. etc.).
How-To
If you have the y-data
- y = [0., 0.5, 1., 1.5, 2., 2.5]
- import math
- print range(math.floor(min(y)), math.ceil(max(y))+1)
- [0, 1, 2, 3]
- yint = range(min(y), math.ceil(max(y))+1)
- matplotlib.pyplot.yticks(yint)
- import matplotlib.pyplot as plt
- import numpy as np
- import math
- x = np.linspace(0, 10, 6)
- y = np.array([0., 0.5, 1., 1.5, 2., 2.5])
- print("y={}".format(y))
- fig, ax = plt.subplots()
- plt.plot(x, y)
- plt.xlabel('time')
- plt.ylabel('Some function of time')
- plt.title("My cool chart")
- plt.show()
With above suggestion, you can have new version below:
- import matplotlib.pyplot as plt
- import numpy as np
- import math
- x = np.linspace(0, 10, 6)
- y = np.array([0., 0.5, 1., 1.5, 2., 2.5])
- print("y={}".format(y))
- fig, ax = plt.subplots()
- plt.plot(x, y)
- plt.xlabel('time')
- plt.ylabel('Some function of time')
- plt.title("My cool chart")
- # Modify ytick labels
- print("min={}; max={}".format(math.floor(min(y.tolist())), math.ceil(max(y.tolist()))))
- yint = range(math.floor(min(y.tolist())), math.ceil(max(y.tolist()))+1)
- plt.yticks(yint)
- plt.show()
Supplement
* FAQ - Modify tick label text
沒有留言:
張貼留言