Python+Matplotlib绘制重叠柱状图
作者:SpikeKing
重叠柱状图 (Overlapped Bar) 是一种比较图,可以将两个柱状图叠加在一起,显示两个相关变量之间的差异,所以本文就来用Matplotlib绘制一个简单的重叠柱状图吧
重叠柱状图 (Overlapped Bar) 是一种比较图,可以将两个柱状图叠加在一起,显示两个相关变量之间的差异。这种图表适合用于展示实际值和期望值之间的对比,例如实际销售额和目标销售额,实际支出和预算支出等。优点是可以直观地看出两个变量的贡献度和占比,也可以节省空间,避免使用双轴图或并列图。缺点是可能会造成视觉混淆,需要注意颜色和透明度的选择,以及图例和标签的清晰显示。
示例效果:

源码如下:
设置plt的尺寸,即plt.figure(figsize=(10,6))。
循环绘制 bar,即plt.bar() 。
设置下标,即plt.xticks() 。
当水平下标太多,影响排列,则关闭下标,即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)) # 设置plt的尺寸
xlabel = xlabel or df.index.name # 标签
N = len(df) # 类别数
M = len(df.columns) # 列数
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: # 如果水平坐标太多,隐藏水平坐标
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 # 低区数值
high = df_all_sum # 高区数值
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()到此这篇关于Python+Matplotlib绘制重叠柱状图的文章就介绍到这了,更多相关Python Matplotlib重叠柱状图内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
