用python畫多維條形圖和投票統計展示

import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as mpatches



def drawbox():
    df={}
    bp={}
    positions = [1,2,3,4]
    df[0]= pd.DataFrame (np.random.rand(4,4),columns =['A','B','C','D'])
    df[1]= pd.DataFrame (np.random.rand(4,4),columns =['A','B','C','D'])
    print(df[0])
    colour=['red','blue']
    fig, ax = plt.subplots()
    for i in [0,1]:
        #bp[i] = df[i].plot.box(ax=ax,positions = positions,color={'whiskers': colour[i],'caps': colour[i],'medians': colour[i],'boxes': colour[i]})
        bp[i] = df[i].plot.line(ax=ax,rot=0)

    red_patch = mpatches.Patch(color='red', label='The red data')
    blue_patch = mpatches.Patch(color='blue', label='The blue data')
    plt.legend(handles=[red_patch, blue_patch])

    plt.show()

def main():
    """
        畫多維條形圖
        np.random.randn 返回有正有負
        np.random.rand 返回0到1之間數字
    """
    data = pd.DataFrame(np.random.rand(6,3),columns=['A','B','C'])
    print(data)
    fig = plt.figure(figsize = (10, 5), dpi = 90) # 聲明畫布1
    ax1 = fig.add_subplot(2,1,1)
    data.plot.bar(ax=ax1,rot=0 )
    plt.title='2個圖例'
    plt.tight_layout()
    plt.grid(linestyle='-.', axis='y')
    plt.legend(shadow=True, loc=(0.1, 0.48), title='圖例', handlelength=1.5, fontsize=14)
    ax2 = fig.add_subplot(2,1,2)
    data.plot.line(ax=ax2,rot=0 )
    #plt.tight_layout()
    plt.grid(linestyle='-.', axis='y')
    plt.legend(labels=['1','2','3'],title='圖例2', loc='best')
    plt.show()

def drawline():
    df= pd.DataFrame (np.random.rand(4,2),columns =['A','B'])
    print(df)
    #fig, ax = plt.subplots()
    fig = plt.figure(figsize = (5, 5), dpi = 90) # 聲明畫布1
    ax=fig.add_subplot(1,1,1)
    df.plot.line(ax=ax,rot=0)
    x=range(4)
    xlabel=[]
    for i in x:
        xlabel.append(str(i))
    plt.xticks(x, xlabel, rotation=0)
    plt.title='2個圖例'
    plt.tight_layout()
    plt.grid(linestyle='-.', axis='y')
    plt.legend(shadow=True, labels=['A','B'],title='圖例', handlelength=1.5, loc='best')
    plt.show()

def drawgroup():
    df= pd.DataFrame ([['tired','yes',6],['tired','no',4],['hungry','yes',8],['hungry','no',2],['painful','yes',7],['painful','no',3]],columns =['question','answer','count'])
    print(df)
    matplotlib.style.use('ggplot')
    df.groupby(['question','answer']).sum().unstack().plot(kind='bar',title='問卷調查', legend=True)
    plt.xticks(rotation=0)
    plt.xlabel('問題')
    plt.ylabel('計數',rotation=0)
    plt.show()


if __name__ == '__main__':
    plt.rcParams['font.family'] = ['Alibaba PuHuiTi']
    plt.rcParams['axes.unicode_minus'] = False
    #main()
    drawgroup()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章