2018年10月9日 星期二

[ Python 常見問題 ] matplotlib - How to force the Y axis to only use integers in Matplotlib?

Source From Here 
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 
  1. y = [0., 0.51., 1.52., 2.5]  
You can use the maximum and minimum values of this data to create a list of natural numbers in this range. For example: 
  1. import math  
  2. print range(math.floor(min(y)), math.ceil(max(y))+1)  
which will yield: 
  1. [0123]  
You can then set the y tick mark locations (and labels) using matplotlib.pyplot.yticks
  1. yint = range(min(y), math.ceil(max(y))+1)  
  2.   
  3. matplotlib.pyplot.yticks(yint)  
For example, we have sample code below: 
  1. import matplotlib.pyplot as plt    
  2. import numpy as np  
  3. import math  
  4.   
  5. x = np.linspace(0106)    
  6. y = np.array([0., 0.51., 1.52., 2.5])    
  7. print("y={}".format(y))  
  8.   
  9. fig, ax = plt.subplots()  
  10.   
  11. plt.plot(x, y)    
  12.   
  13. plt.xlabel('time')    
  14. plt.ylabel('Some function of time')    
  15. plt.title("My cool chart")    
  16.   
  17. plt.show()  



With above suggestion, you can have new version below: 
  1. import matplotlib.pyplot as plt    
  2. import numpy as np  
  3. import math  
  4.   
  5. x = np.linspace(0106)    
  6. y = np.array([0., 0.51., 1.52., 2.5])    
  7. print("y={}".format(y))  
  8.   
  9. fig, ax = plt.subplots()  
  10.   
  11. plt.plot(x, y)    
  12.   
  13. plt.xlabel('time')    
  14. plt.ylabel('Some function of time')    
  15. plt.title("My cool chart")    
  16.   
  17. # Modify ytick labels  
  18. print("min={}; max={}".format(math.floor(min(y.tolist())), math.ceil(max(y.tolist()))))  
  19. yint = range(math.floor(min(y.tolist())), math.ceil(max(y.tolist()))+1)  
  20. plt.yticks(yint)  
  21.   
  22. plt.show()  
You can achieve your goal: 


Supplement 
FAQ - Modify tick label text

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...