2021年4月15日 星期四

[ Python 常見問題 ] How to display the value of each bar in a bar chart using Matplotlib?

 Source From Here

Preface
In this article, we are going to see how to display the value of each bar in a bar chat using Matplotlib. There are two different ways to display the values of each bar in a bar chart in matplotlib –
* Using matplotlib.axes.Axes.text() function.
* Use matplotlib.pyplot.text() function.


HowTo

Example 1: Using matplotlib.axes.Axes.text() function:
This function is basically used to add some text to the location in the chart. This function return string, this is always used with the syntax “for index, value in enumerate(iterable)” with iterable as the list of bar values to access each index, value pair in iterable so at it can add the text at each bar:
  1. import os  
  2. import numpy as np  
  3. import matplotlib.pyplot as plt  
  4.     
  5. x = [01234567]  
  6. y = [160167171301204010570]  
  7. fig, ax = plt.subplots()  
  8. width = 0.75  
  9. ind = np.arange(len(y))  
  10.     
  11. ax.barh(ind, y, width, color = "green")  
  12.     
  13. for i, v in enumerate(y):  
  14.     ax.text(v + 3, i + .25, str(v),   
  15.             color = 'blue', fontweight = 'bold')  
  16. plt.show()  


Example 2: Use matplotlib.pyplot.text() function:
Call matplotlib.pyplot.barh(x, height) with x as a list of bar names and height as a list of bar values to create a bar chart. Use the syntax “for index, value in enumerate(iterable)” with iterable as the list of bar values to access each index, value pair in iterable. At each iteration, call matplotlib.pyplot.text(x, y, s) with x as value, y as index, and s as str(value) to label each bar with its size.
  1. import matplotlib.pyplot as plt  
  2. x = ["A""B""C""D"]  
  3. y = [1234]  
  4. plt.barh(x, y)  
  5.     
  6. for index, value in enumerate(y):  
  7.     plt.text(value, index,  
  8.              str(value))  
  9.     
  10. plt.show()  



沒有留言:

張貼留言

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