2019年8月19日 星期一

[ Python 常見問題 ] Writing numerical values on the plot with Matplotlib

Source From Here
Question
Is it possible, with Matplotlib, to print the values of each point on the graph? For example, if I have:
  1. import numpy as np  
  2. from matplotlib import pyplot as plt  
  3.   
  4. x = np.arange(0,10)  
  5. y = np.array([5,3,4,2,7,5,4,6,3,2])  
  6. plt.plot(x,y)  


How can I display y values on the plot (e.g. print a 5 near the (0,5) point, print a 3 near the (1,3) point, etc.)?

How-To
You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this:
  1. import numpy as np  
  2. from matplotlib import pyplot as plt  
  3.   
  4. x = np.arange(10)  
  5. y = np.array([5,3,4,2,7,5,4,6,3,2])  
  6.   
  7. fig = plt.figure()  
  8. ax = fig.add_subplot(111)  
  9. ax.set_ylim(0,10)  
  10. plt.plot(x,y)  
  11. for i,j in zip(x,y):  
  12.     ax.annotate(str(j),xy=(i,j))  
  13.   
  14. plt.show()  


If you want the annotations offset a little, you could change the annotate line to something like:
  1. ax.annotate(str(j),xy=(i,j+0.5))  


沒有留言:

張貼留言

[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...