Python+Matplotlib繪制發(fā)散條形圖的示例代碼
發(fā)散條形圖(Diverging Bar)是一種用于顯示數(shù)據(jù)分布的圖表,可以幫助我們比較不同類別或分組的數(shù)據(jù)的差異和相對性。發(fā)散條形圖的特點(diǎn)是,以一個中心點(diǎn)為基準(zhǔn),將數(shù)據(jù)分為兩個方向,通常用不同的顏色來表示正負(fù)或高低。
示例如下:

源碼如下:
#!/usr/bin/env python
# -- coding: utf-8 --
"""
Copyright (c) 2022. All rights reserved.
Created by C. L. Wang on 2023/6/6
"""
import os
import matplotlib.pyplot as plt
from myutils.project_utils import read_excel_to_df
from root_dir import DATA_DIR
def diverging_bar(
df, value_col, y_ticks_col, x_label="", y_label="", title="",
is_grid=False, is_show=False, save_name=""
):
"""
默認(rèn)數(shù)據(jù)存儲至 df["diff"] 字段
:param df: 數(shù)據(jù)
:param value_col: 數(shù)值列
:param y_ticks_col: 標(biāo)簽列
:return:
"""
# 準(zhǔn)備數(shù)據(jù)
df['colors'] = ['red' if x < 0 else 'green' for x in df[value_col]]
df.sort_values(value_col, inplace=True)
df.reset_index(inplace=True)
plt.figure(figsize=(12, 12), dpi=80)
# 設(shè)置數(shù)據(jù)
plt.hlines(y=df.index, xmin=0, xmax=df[value_col], color=df.colors, alpha=0.4, linewidth=8)
# 設(shè)置標(biāo)簽
# plt.yticks(df.index, df[y_ticks_col], fontsize=12) # y軸
plt.yticks(df.index, df[y_ticks_col], fontsize=12) # y軸
# 設(shè)置圖表說明
if x_label:
plt.gca().set(xlabel=f'${x_label}$')
if y_label:
plt.gca().set(ylabel=f'${y_label}$') # $$符號表示斜體
plt.title(title, fontdict={'size': 12})
if is_grid: # 顯示網(wǎng)格
plt.grid(linestyle='--', alpha=0.5)
if save_name:
plt.savefig(save_name, bbox_inches='tight', format='png', transparent=True)
if is_show:
plt.show()
def main():
# df = read_excel_to_df(os.path.join(DATA_DIR, "ourbest_20230605_dockq_9_final.xls"))
df = read_excel_to_df(os.path.join(DATA_DIR, "ourbest_20230601_tmscore_56.xls"))
x1 = df["m0-score"]
x2 = df["m2-score"]
# x2 = df["m1-score"]
df["diff"] = x2 - x1
df.info()
diverging_bar(
df, value_col="diff", y_ticks_col="target",
x_label="DockQ", y_label="Target", title="",
is_show=True, save_name="xxx.png")
if __name__ == '__main__':
main()
到此這篇關(guān)于Python+Matplotlib繪制發(fā)散條形圖的示例代碼的文章就介紹到這了,更多相關(guān)Python Matplotlib發(fā)散條形圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于Python核心框架tornado的異步協(xié)程的2種方法詳解
今天小編就為大家分享一篇關(guān)于Python核心框架tornado的異步協(xié)程的2種方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
Spring http服務(wù)遠(yuǎn)程調(diào)用實(shí)現(xiàn)過程解析
這篇文章主要介紹了Spring http服務(wù)遠(yuǎn)程調(diào)用實(shí)現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-06-06
python 基礎(chǔ)學(xué)習(xí)第二彈 類屬性和實(shí)例屬性
本人c程序員,最近開始學(xué)python,深深的被python的強(qiáng)大所吸引,今后也會把學(xué)到的點(diǎn)點(diǎn)滴滴記錄下來,現(xiàn)在分享一下關(guān)于類屬性和實(shí)例屬性的一些問題,很基礎(chǔ)的東西2012-08-08

