日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python如何利用matplotlib繪制并列雙柱狀圖并標注數(shù)值_python

作者:小白白程序員 ? 更新時間: 2022-06-26 編程語言

項目場景:

Python項目需要畫兩組數(shù)據(jù)的雙柱狀圖,以下以一周七天兩位小朋友吃糖顆數(shù)為例進行演示,用matplotlib庫實現(xiàn)

代碼:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

def drawHistogram():
    matplotlib.rc("font", family='MicroSoft YaHei')
    list1 = np.array([5, 2, 1, 0, 8, 0, 6])   # 柱狀圖第一組數(shù)據(jù)
    list2 = np.array([9, 5, 1, 2, 9, 2, 0])   # 柱狀圖第二組數(shù)據(jù)
    length = len(list1)
    x = np.arange(length)   # 橫坐標范圍
    listDate = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"]

    plt.figure()
    total_width, n = 0.8, 2   # 柱狀圖總寬度,有幾組數(shù)據(jù)
    width = total_width / n   # 單個柱狀圖的寬度
    x1 = x - width / 2   # 第一組數(shù)據(jù)柱狀圖橫坐標起始位置
    x2 = x1 + width   # 第二組數(shù)據(jù)柱狀圖橫坐標起始位置

    plt.title("一周每天吃悠哈軟糖顆數(shù)柱狀圖")   # 柱狀圖標題
    # plt.xlabel("星期")   # 橫坐標label 此處可以不添加
    plt.ylabel("吃悠哈軟糖顆數(shù)(個)")   # 縱坐標label
    plt.bar(x1, list1, width=width, label="小s吃糖數(shù)")
    plt.bar(x2, list2, width=width, label="小y吃糖數(shù)")
    plt.xticks(x, listDate)   # 用星期幾替換橫坐標x的值
    plt.legend()   # 給出圖例
    plt.show()

if __name__ == '__main__':
    drawHistogram()

效果圖:

一周每天吃悠哈軟糖顆數(shù)柱狀圖

擴展功能及代碼:

擴展功能一

如果橫坐標標簽比較長或是文字比較多,以一定角度傾斜展示,上文中代碼這一行:

plt.xticks(x, listDate)

可以改為:

plt.xticks(x, listDate, rotation=30) # rotation為標簽旋轉角度

橫坐標標簽旋轉30°效果如下:

橫坐標label旋轉30度

橫坐標標簽旋轉90°效果如下:

橫坐標label旋轉90度

擴展功能二

如果希望具體的數(shù)據(jù)值展示在柱狀圖中,可以在代碼 plt.legend() 前加入如下代碼:

for a, b in zip(x1, list1):
	plt.text(a, b + 0.1, '%.0f' % b, ha='center', va='bottom', fontsize=7)

for a, b in zip(x2, list2):
	plt.text(a, b + 0.1, '%.0f' % b, ha='center', va='bottom', fontsize=7)

加了具體數(shù)值的柱狀圖效果如下:

加了數(shù)值的柱狀圖

補充:Python畫圖實現(xiàn)同一結點多個柱狀圖

import numpy as np
x = [1,2]   #橫坐標
y = [3,4]   #第一個縱坐標
y1 = [5,6]   #第二個縱坐標
x = np.arange(len(x))  #首先用第一個的長度作為橫坐標
width = 0.05    #設置柱與柱之間的寬度
fig,ax = plt.subplots()
ax.bar(x,y,width,alpha = 0.9)
ax.bar(x+width,y1,width,alpha = 0.9,color= 'red')
ax.set_xticks(x +width/2)#將坐標設置在指定位置
ax.set_xticklabels(x)#將橫坐標替換成
plt.show()

后續(xù)有時間再繼續(xù)補充擴展功能哦~

總結

原文鏈接:https://blog.csdn.net/qq_39691492/article/details/119422424

欄目分類
最近更新