python matplotlib 柱狀圖實現

def test_chart():
    domain_name = ["1", "2", "3", "4", "5"]
    domain_in = [148.44, 221.01, 242.62, 591.47, 290.44]
    median_list = [118.0, 189.5, 235.0, 488.0, 202.0]
    task_id = 5
    img_name = "in_avg.png"
    # 設置y軸的最大值
    in_max = sorted(domain_in)[-1:][0] + 100
    print(len(domain_name), len(domain_in))
    # 生成list[0,1,2,3,4.....]
    x = list(range(len(domain_in)))
    b_list = list(range(len(median_list)))
    # 生成柱狀圖的寬度
    total_width, n = 0.8, 1.5
    width = total_width / n
    width = 0.4
    b_width = width + 0.4
    # 畫布大小
    fig = plt.figure(figsize=(7, 3))
    # 設置中文顯示,否則出現亂碼!
    plt.rc('font', family='SimHei', size=12)
    xlim = (0, len(domain_in))
    ylim = (0, in_max)
    # 添加子圖,作爲子圖佈置的一部分,將座標軸添加到圖中。
    ax = fig.add_subplot(111, xlim=xlim, ylim=ylim,
                         autoscale_on=False)
    # 設置柱狀圖開始的位置
    for i in range(len(x)):
        x[i] = x[i] + width
    for i in range(len(b_list)):
        b_list[i] = b_list[i] + b_width
    # 旋轉角度
    plt.xticks(rotation=280)
    # 設置值
    b = plt.bar(x, domain_in, width=width, label='平均數', tick_label=domain_name, fc='dodgerblue')
    c = plt.bar(b_list, median_list, width=width, label='中位數', tick_label=domain_name, fc='orange')
    plt.axhline(y=500, lw=1, c="red")  # 添加水平直線,加上參數“ls=":"”表示是虛線
    plt.legend()
    ax.set_aspect('auto')
    ax.set_title("時間")
    ax.set_xlabel("X軸")
    ax.set_ylabel("y軸")
    # 設置柱狀圖顯示值
    autolabel(b)
    autolabel(c)
    folder = settings.CHART_IMG_URL + str(task_id)
    if not os.path.exists(folder):
        os.mkdir(folder)
    img_path = folder + '/' + str(task_id) + img_name
    plt.savefig(img_path, bbox_inches='tight')
    show()
def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        # plt.text(rect.get_x()+rect.get_width()/2.-0.2, 1.03*height, '%s' % int(height))
        plt.text(rect.get_x() + rect.get_width() / 2. - 0.2, 1.03 * height, '%s' % int(height))

顯示圖如下:

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