Python+Matplotlib繪制重疊柱狀圖
重疊柱狀圖 (Overlapped Bar) 是一種比較圖,可以將兩個(gè)柱狀圖疊加在一起,顯示兩個(gè)相關(guān)變量之間的差異。這種圖表適合用于展示實(shí)際值和期望值之間的對(duì)比,例如實(shí)際銷售額和目標(biāo)銷售額,實(shí)際支出和預(yù)算支出等。優(yōu)點(diǎn)是可以直觀地看出兩個(gè)變量的貢獻(xiàn)度和占比,也可以節(jié)省空間,避免使用雙軸圖或并列圖。缺點(diǎn)是可能會(huì)造成視覺(jué)混淆,需要注意顏色和透明度的選擇,以及圖例和標(biāo)簽的清晰顯示。
示例效果:
源碼如下:
設(shè)置plt的尺寸,即plt.figure(figsize=(10,6))。
循環(huán)繪制 bar,即plt.bar() 。
設(shè)置下標(biāo),即plt.xticks() 。
當(dāng)水平下標(biāo)太多,影響排列,則關(guān)閉下標(biāo),即plt.xticks([])。
df的排序邏輯,即df.sort_values(by=["ratio"], ascending=True)。
#!/usr/bin/env python # -- coding: utf-8 -- """ Copyright (c) 2022. All rights reserved. Created by C. L. Wang on 2023/6/5 """ import os.path import matplotlib.pyplot as plt import numpy as np import pandas as pd from myutils.project_utils import read_excel_to_df from root_dir import DATA_DIR def overlapped_bar(df, show=False, width=0.75, alpha=.5, title='', xlabel='', ylabel='', hide_xsticks=True, **plot_kwargs): """ Like a stacked bar chart except bars on top of each other with transparency. :param df: data df :param show: show in ide :param width: bar width """ plt.figure(figsize=(10, 6)) # 設(shè)置plt的尺寸 xlabel = xlabel or df.index.name # 標(biāo)簽 N = len(df) # 類別數(shù) M = len(df.columns) # 列數(shù) indices = np.arange(N) colors = ['steelblue', 'firebrick', 'darksage', 'goldenrod', 'gray'] * int(M / 5. + 1) # 顏色 for i, label, color in zip(range(M), df.columns, colors): kwargs = plot_kwargs kwargs.update({'color': color, 'label': label}) plt.bar(indices, df[label], width=width, alpha=alpha if i else 1, **kwargs) plt.xticks(indices + .5 * width, ['{}'.format(idx) for idx in df.index.values]) plt.legend() plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) if hide_xsticks: # 如果水平坐標(biāo)太多,隱藏水平坐標(biāo) plt.xticks([]) if show: plt.show() return plt.gcf() def draw_bars(): df = read_excel_to_df(os.path.join(DATA_DIR, "msa_all_counts.xlsx")) df["ratio"] = df["all_sum"] / df["sum"] df = df.sort_values(by=["ratio"], ascending=True) # 從小到大排序 df_sum = df["sum"] / df["sum"] df_all_sum = df["all_sum"] / df["sum"] avg = round(np.average(df_all_sum), 4) std = round(float(np.std(df_all_sum)), 4) print(f"[Info] improve ratio: {avg}±{std}") # 獲取比例 low = df_sum # 低區(qū)數(shù)值 high = df_all_sum # 高區(qū)數(shù)值 df = pd.DataFrame(np.matrix([high, low]).T, columns=['Ours', 'AF2']) overlapped_bar(df, xlabel="target", ylabel="times", show=True) if __name__ == '__main__': draw_bars()
到此這篇關(guān)于Python+Matplotlib繪制重疊柱狀圖的文章就介紹到這了,更多相關(guān)Python Matplotlib重疊柱狀圖內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
手把手教你用Python中的Linting提高代碼質(zhì)量
Python是一種不斷發(fā)展的語(yǔ)言,隨著它的演化和擴(kuò)展,可用工具和開(kāi)發(fā)策略的數(shù)量也在增加,近來(lái)流行的一個(gè)過(guò)程是linting—檢查代碼的潛在問(wèn)題,下面這篇文章主要給大家介紹了關(guān)于用Python中Linting提高代碼質(zhì)量的相關(guān)資料,需要的朋友可以參考下2023-01-01使用Django搭建web服務(wù)器的例子(最最正確的方式)
今天小編就為大家分享一篇使用Django搭建web服務(wù)器的例子(最最正確的方式),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-08-08python?flask框架中多種查詢參數(shù)的獲取方式
這篇文章主要介紹了pythonflask框架的生命周期以及多種查詢參數(shù)的獲取方式,文章通過(guò)代碼示例和圖文講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-03-03Python中內(nèi)存管理機(jī)制與優(yōu)化技巧分享
這篇文章主要來(lái)和大家簡(jiǎn)單聊一聊Python中的內(nèi)存管理,從而可以幫助大家寫出更高效,優(yōu)化內(nèi)存占用的 Python 代碼,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-04-04