溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Matplotlib繪制條形圖的方法有哪些

發(fā)布時間:2022-03-22 09:08:23 來源:億速云 閱讀:214 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹了Matplotlib繪制條形圖的方法有哪些的相關(guān)知識,內(nèi)容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇Matplotlib繪制條形圖的方法有哪些文章都會有所收獲,下面我們一起來看看吧。

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    from matplotlib import font_manager

    一、一般條形圖

    一般條形圖使用 pyplot.bar()函數(shù)繪制,其形式及參數(shù)如下:

    matplotlib.pyplot.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)
    主要參數(shù)解釋:
    # x:一個數(shù)組或者列表,代表需要繪制的條形圖的x軸的坐標點。
    # height:一個數(shù)組或者列表,代表需要繪制的條形圖y軸的坐標點。
    # width:每一個條形圖的寬度,默認是0.8的寬度。
    # bottom:y軸的基線,默認是0,也就是距離底部為0.
    # align:對齊方式,{'center','edge'},默認是center,居中對齊;edge為靠邊對齊,具體靠右邊還是靠左邊,看width的正負。
    # color:條形圖的顏色。
    # edgecolor : 條形圖邊框的顏色。
    # linewidth  : 條形圖邊框的寬度。如果為 0,則不繪制邊框

    示例:

    某天電影票房數(shù)據(jù):

    movies = {
        "流浪地球":40.78,
        "飛馳人生":15.77,
        "瘋狂的外星人":20.83,
        "新喜劇之王":6.10,
        "廉政風(fēng)云":1.10,
        "神探蒲松齡":1.49,
        "小豬佩奇過大年":1.22,
        "熊出沒·原始時代":6.71
    }

    直接通過獲取字典的鍵值作為x,y軸數(shù)據(jù)

    #票房單位億元
    movies = {
        "流浪地球":40.78,
        "飛馳人生":15.77,
        "瘋狂的外星人":20.83,
        "新喜劇之王":6.10,
        "廉政風(fēng)云":1.10,
        "神探蒲松齡":1.49,
        "小豬佩奇過大年":1.22,
        "熊出沒·原始時代":6.71
    }
    # 中文顯示問題
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    plt.rcParams['font.size'] = 13
    # 設(shè)置圖大小
    plt.figure(figsize=(15,8))
    
    x = list(movies.keys()) # 獲取x軸數(shù)據(jù)(字典的鍵)
    y = list(movies.values()) # 獲取y軸數(shù)據(jù)(字典的值)
    
    plt.bar(x,y,width=0.5,bottom=0,align='edge',color='g',edgecolor ='r',linewidth=2)
    
    # 繪制標題
    plt.title("電影票房數(shù)據(jù)",size=26)
    
    # 設(shè)置軸標簽
    plt.xlabel("電影名",size=28)
    plt.ylabel("票房/億",size=28)
    
    plt.show()

    Matplotlib繪制條形圖的方法有哪些

    也可以利用字典創(chuàng)建DataFrame索引,通過data參數(shù)傳入

    #票房單位億元
    movies = {
        "流浪地球":40.78,
        "飛馳人生":15.77,
        "瘋狂的外星人":20.83,
        "新喜劇之王":6.10,
        "廉政風(fēng)云":1.10,
        "神探蒲松齡":1.49,
        "小豬佩奇過大年":1.22,
        "熊出沒·原始時代":6.71
    }
    movies_df = pd.DataFrame(data={"name":list(movies.keys()),"tickes":list(movies.values())}) #通過字典創(chuàng)建DataFrame索引
    font = font_manager.FontProperties(fname='C:\Windows\Fonts\STSONG.TTF',size=12)  # 使用font_manager模塊設(shè)置中文
    
    # 設(shè)置圖的大小,傳入x,y
    plt.figure(figsize=(14,5))
    
    # 使用plt.bar()繪制條形圖
    plt.bar("name","tickes",data=movies_df,width=0.5,bottom=0,align='edge',color='g',edgecolor ='r',linewidth=2)
    
    #設(shè)置X軸刻度,設(shè)置字體,也可以設(shè)置字體大小size
    plt.xticks(fontproperties=font)
    
    # 設(shè)置標題
    plt.title("電影票房數(shù)據(jù)",size=30)
    #設(shè)置X,Y軸名字
    plt.ylabel('票房',fontproperties=font,size=25)
    plt.xlabel('影片名字',fontproperties=font,size=25)
    
    #設(shè)置Y刻度
    plt.yticks(range(0,50,5),["%d"%x for x in range(0,50,5)],fontproperties=font1,size=20)
    
    # 只保留圖形信息
    plt.show()

    Matplotlib繪制條形圖的方法有哪些

    二、橫向條形圖

    橫向條形圖需要使用barh()這個跟bar非常的類似,只不過把方向進行旋轉(zhuǎn)。參數(shù)也和pyplot.bar()類似

    matplotlib.pyplot.barh(y, width, height=0.8, left=None, *, align='center', **kwargs)
    # 主要參數(shù)解釋:
    # y:數(shù)組或列表,代表需要繪制的條形圖在y軸上的坐標點。
    # width:數(shù)組或列表,代表需要繪制的條形圖在x軸上的值(也就是長度)。
    # height:條形圖的高度(寬度),默認是0.8。
    # left:條形圖的基線,也就是距離y軸的距離。默認為0

    示例:

    plt.barh()

    movies = {
        "流浪地球":40.78,
        "飛馳人生":15.77,
        "瘋狂的外星人":20.83,
        "新喜劇之王":6.10,
        "廉政風(fēng)云":1.10,
        "神探蒲松齡":1.49,
        "小豬佩奇過大年":1.22,
        "熊出沒·原始時代":6.71
    }
    font2 = font_manager.FontProperties(fname='C:\Windows\Fonts\STSONG.TTF')
    x1 = list(movies.keys())
    y1 = list(movies.values())
    
    # 設(shè)置圖的大小
    plt.figure(figsize=(10,5))
    
    # 使用plt.barh()
    plt.barh(x1,y1,height=0.7,left=0,color='c',edgecolor='r')
    
    #設(shè)置Y軸刻度,設(shè)置字體,也可以設(shè)置字體大小size
    plt.yticks(fontproperties=font2,size=20)
    
    plt.xlabel("票房/億",size=20)
    
    # 設(shè)置標題
    plt.title("電影票房數(shù)據(jù)",size=30)
    
    # 只保留圖形信息
    plt.show()

    Matplotlib繪制條形圖的方法有哪些

    Axes.barh(y, width, height=0.8, left=None, *, align='center', **kwargs)

    另外,還可通過返回的axes對象繪制圖形

    movies = {
        "流浪地球":40.78,
        "飛馳人生":15.77,
        "瘋狂的外星人":20.83,
        "新喜劇之王":6.10,
        "廉政風(fēng)云":1.10,
        "神探蒲松齡":1.49,
        "小豬佩奇過大年":1.22,
        "熊出沒·原始時代":6.71
    }
    
    font2 = font_manager.FontProperties(fname='C:\Windows\Fonts\STSONG.TTF')
    mdf = pd.DataFrame(data={"name":list(movies.keys()),"tickes":list(movies.values())})
    
    fig,axes = plt.subplots()  
    
    # 通過返回的axes對象繪制圖形
    axes.barh("name","tickes",data = mdf,height=0.6,left=0,color='c',edgecolor='r')
    
    #設(shè)置Y軸刻度,設(shè)置字體,也可以設(shè)置字體大小size
    plt.yticks(fontproperties=font2,size=20)
    
    plt.xlabel("票房/億",size=24)
    
    # 設(shè)置標題
    plt.title("電影票房數(shù)據(jù)",size=27)
    
    # 只保留圖形信息
    plt.show()

    Matplotlib繪制條形圖的方法有哪些

    三、分組條形圖的繪制

    五天的電影票房數(shù)據(jù)(假設(shè)日期為1.1-1.5):并轉(zhuǎn)換為DataFrame索引

    movies = {
        "流浪地球":[2.01,4.59,7.99,11.83,16],
        "飛馳人生":[3.19,5.08,6.73,8.10,9.35],
        "瘋狂的外星人":[4.07,6.92,9.30,11.29,13.03],
        "新喜劇之王":[2.72,3.79,4.45,4.83,5.11],
        "廉政風(fēng)云":[0.56,0.74,0.83,0.88,0.92],
        "神探蒲松齡":[0.66,0.95,1.10,1.17,1.23],
        "小豬佩奇過大年":[0.58,0.81,0.94,1.01,1.07],
        "熊出沒·原始時代":[1.13,1.96,2.73,3.42,4.05]
    }
    mdf = pd.DataFrame(movies)  
    mdf

    Matplotlib繪制條形圖的方法有哪些

    繪制分組條形圖思路:先選出每天所有電影的票房數(shù)據(jù),可使用DataFrame.iloc[]方法獲取,例如

    # 獲取第一天票房數(shù)據(jù)
    mdf.iloc[0]
    流浪地球        2.01
    飛馳人生        3.19
    瘋狂的外星人      4.07
    新喜劇之王       2.72
    廉政風(fēng)云        0.56
    神探蒲松齡       0.66
    小豬佩奇過大年     0.58
    熊出沒·原始時代    1.13
    Name: 0, dtype: float64

    然后按天進行繪制,這里需要確定一個中心點作為中間日期的條形圖位置(這里為第三天),有多少部電影就需要多少個中心點,可使用np.arange(len(movies))獲取x軸刻度作為中心點。最后根據(jù)日期按條形圖的寬度調(diào)整條形圖位置即可。

    plt.figure(figsize=(15,5))
    # 設(shè)置X軸刻度為一個數(shù)組(有廣播功能)
    xticks = np.arange(len(movies)) 
    
    #設(shè)置字體
    font = font_manager.FontProperties(fname='C:\Windows\Fonts\STSONG.TTF')
    
    # 設(shè)置條形圖寬度
    bar_width = 0.15
    
    #設(shè)置第一天所有影片條形圖的位置
    plt.bar(xticks-2*bar_width,mdf.iloc[0],width=bar_width,color='pink') # iloc[]取DataFrame的一行
    #設(shè)置第二天所有影片條形圖的位置 
    plt.bar(xticks-bar_width,mdf.iloc[1],width=bar_width)
    #設(shè)置第三天所有影片條形圖的位置,默認在[0 1 2 3 4 5 6 7]center處
    plt.bar(xticks,mdf.iloc[2],width=bar_width)
    #設(shè)置第四天所有影片條形圖的位置
    plt.bar(xticks+bar_width,mdf.iloc[3],width=bar_width)
    #設(shè)置第五天所有影片條形圖的位置
    plt.bar(xticks+2*bar_width,mdf.iloc[4],width=bar_width)
    
    # 設(shè)置X軸信息
    plt.xticks(xticks,mdf.columns,fontproperties=font,size=15)
    #設(shè)置Y刻度
    plt.yticks(range(0,20,2),["%d"%x for x in range(0,20,2)],fontproperties=font,size=16)
    
    #設(shè)置X,Y軸名字
    plt.ylabel('票房/億',fontproperties=font,size=30)
    plt.xlabel('影片名字',fontproperties=font,size=30)
    
    # 設(shè)置標題
    plt.title("五日票房數(shù)據(jù)",fontproperties=font,size=30)
    
    # 只保留圖形信息
    plt.show()

    Matplotlib繪制條形圖的方法有哪些

    使用循環(huán)繪制每日數(shù)據(jù)

    plt.figure(figsize=(16,5))
    # 設(shè)置X軸刻度為一個數(shù)組(有廣播功能)
    #xticks1 = np.arange(len(movies)) # 這樣設(shè)置每部電影X軸的距離是1,如果5個條形圖寬度之后大于1會和其他電影重疊,可以設(shè)置步長
    xticks1 = np.arange(0,7*len(movies),7) # 改變步長,要在設(shè)置X軸信息處改變xticks(步長*ticks labels)的第一個參數(shù),否則對應(yīng)不上
    
    #設(shè)置字體
    font4 = font_manager.FontProperties(fname='C:\Windows\Fonts\STSONG.TTF')
    
    # 設(shè)置條形圖寬度
    bar_width2 = 1.05
    
    #使用循環(huán)畫出前五天的條形圖
    for index in mdf.index:
       # plt.bar(xticks1+(-2+index)*bar_width2,mdf.iloc[index],width=bar_width2,label='第%d天票房'%(index+1))
        xs = xticks1+(-2+index)*bar_width2 # 在X軸的位置
        day_tickets = mdf.iloc[index]
        plt.bar(xs,day_tickets,width=bar_width*7,label="第%d天票房"%(index+1))
        #設(shè)置注釋文本
        # zip(day_tickets,xs)打包為元素為元組的列表,元素個數(shù)與最短的列表一致
        for ticket,x in zip(day_tickets,xs):   # ticket是day_tickets列表的值,x是xs的值
            plt.annotate(ticket,xy=(x,ticket),xytext=(x-0.2,ticket+0.1))
    
    
    # 設(shè)置X軸信息
    plt.xticks(7*xticks,mdf.columns,fontproperties=font4,size=15)
    
    #設(shè)置X,Y軸名字
    plt.ylabel('票房/億',fontproperties=font4,size=25)
    plt.xlabel('影片名字',fontproperties=font4,size=25)
    
    # 設(shè)置標題
    plt.title("五日票房數(shù)據(jù)",fontproperties=font4,size=30)
    
    # 設(shè)置圖例
    font4.set_size(15) # 圖例無size屬性,可以在字體設(shè)置font4中改大小(或者font.set_size():只改圖例
    plt.legend(prop=font4)  # 根據(jù)bar()函數(shù)的中的label標簽進行設(shè)置,不可缺少
    
    # 設(shè)置網(wǎng)格
    plt.grid()
    
    # 只保留圖形信息
    plt.show()

    Matplotlib繪制條形圖的方法有哪些

    四、堆疊條形圖繪制

    堆疊條形圖就是在已有數(shù)據(jù)基礎(chǔ)位置上進行繪制圖形,使用bottom參數(shù),以已有數(shù)據(jù)作為新數(shù)據(jù)的基地進行新數(shù)據(jù)的繪制,可以達到調(diào)整條形圖的位置的目的。

    示例:

    # 男女不同組別的等分情況
    menMeans = (20, 35, 30, 35, 27)
    womenMeans = (25, 32, 34, 20, 25)
    groupNames = ('G1','G2','G3','G4','G5')
    
    xs = np.arange(len(menMeans))  # 有多少個組
    
    font5 = font_manager.FontProperties(fname='C:\Windows\Fonts\STSONG.TTF',size=16)
    
    plt.figure(figsize=(15,7))
    
    # 繪制男性得分
    plt.bar(xs,menMeans,label='男性得分',width=0.4)
    
    # 繪制女性得分,以男性得分的最大值為基底
    plt.bar(xs,womenMeans,bottom=menMeans,label='女性得分',width=0.4)
    
    #設(shè)置圖例
    plt.legend(prop=font5)  # 根據(jù)bar()函數(shù)的中的label標簽進行設(shè)置
    
    # 設(shè)置X軸刻度名稱
    plt.xticks(xs,groupNames)
    
    # 設(shè)置標簽
    plt.xlabel("組別",fontproperties=font5,size=23)
    plt.ylabel("得分",fontproperties=font5,size=23)
    
    # 設(shè)置標題
    plt.title("男女不同組別得分",fontproperties=font5,size=28)
    
    # 只保留圖形
    plt.show()

    Matplotlib繪制條形圖的方法有哪些

    關(guān)于“Matplotlib繪制條形圖的方法有哪些”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“Matplotlib繪制條形圖的方法有哪些”知識都有一定的了解,大家如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

    向AI問一下細節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI