Matplotlib的概念這裡就不多介紹了
小編之前也和大家分享過python使用matplotlib實現的折線圖和製餅圖效果,感興趣的朋友們也可以點擊查看,下面來看看python使用matplotlib繪製柱狀圖的方法吧,具體如下:
1. 基本的柱狀圖
import matplotlib.pyplot as plt data = [5, 20, 15, 25, 10] plt.bar(range(len(data)), data) plt.show()
(left - width / 2, bottom)
為左下角位置為右上角位置
bar(left, height, width=0.8, bottom=None, **kwargs)
import matplotlib.pyplot as plt data = [5, 20, 15, 25, 10] plt.bar([0.3, 1.7, 4, 6, 7], data, width=0.6, bottom=[10, 0, 5, 0, 5]) plt.show()
.
透過facecolor(或fc)關鍵字參數可以設定柱體顏色,例如:import matplotlib.pyplot as plt data = [5, 20, 15, 25, 10] plt.bar(range(len(data)), data, fc='g') plt.show()
import matplotlib.pyplot as plt data = [5, 20, 15, 25, 10] plt.bar(range(len(data)), data, color='rgb') # or `color=['r', 'g', 'b']` plt.show()
import matplotlib.pyplot as plt data = [5, 20, 15, 25, 10] plt.bar(range(len(data)), data, ec='r', ls='--', lw=2) plt.show()
通過bottom參數,可以繪製堆疊長條圖。例如:
import matplotlib.pyplot as plt data = [5, 20, 15, 25, 10] plt.bar(range(len(data)), data, ec='k', lw=1, hatch='o') plt.show()
5. 並列柱狀圖
繪製並列柱狀圖與堆疊柱狀圖類似,都是多柱狀圖組和大小即可。例如:import matplotlib.pyplot as plt data = [5, 20, 15, 25, 10] labels = ['Tom', 'Dick', 'Harry', 'Slim', 'Jim'] plt.bar(range(len(data)), data, tick_label=labels) plt.show()
6. 條形圖
使用barh方法繪製條形圖。例如:import numpy as np import matplotlib.pyplot as plt size = 5 x = np.arange(size) a = np.random.random(size) b = np.random.random(size) plt.bar(x, a, label='a') plt.bar(x, b, bottom=a, label='b') plt.legend() plt.show()
import numpy as np import matplotlib.pyplot as plt size = 5 x = np.arange(size) a = np.random.random(size) b = np.random.random(size) c = np.random.random(size) total_width, n = 0.8, 3 width = total_width / n x = x - (total_width - width) / 2 plt.bar(x, a, width=width, label='a') plt.bar(x + width, b, width=width, label='b') plt.bar(x + 2 * width, c, width=width, label='c') plt.legend() plt.show()
7. 正負長條圖
import matplotlib.pyplot as plt data = [5, 20, 15, 25, 10] plt.barh(range(len(data)), data) plt.show()
更多python使用matplotlib繪製長條圖教學相關文章請關注PHP中文網!