-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbar.py
More file actions
68 lines (53 loc) · 1.55 KB
/
bar.py
File metadata and controls
68 lines (53 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import matplotlib.pyplot as plt
from save import save_fig
def plot_bar(
data: dict,
save_path=None,
figsize=(4, 3),
xlabel="",
ylabel="",
rotate_xticks=45,
y_lim=1.1,
show_values=True,
sort=False,
color=None,
):
"""
Plot a generic categorical bar chart.
Args:
data (dict): {category_name: value}
save_path (str or None): path to save figure (pdf)
figsize (tuple): figure size in inches
xlabel (str)
ylabel (str)
rotate_xticks (int)
y_lim (float): y-axis limit multiplier
show_values (bool)
sort (bool)
color (str or None): bar color
"""
if sort:
items = sorted(data.items(), key=lambda x: x[1], reverse=True)
else:
items = data.items()
categories, values = zip(*items)
fig, ax = plt.subplots(figsize=figsize)
bars = ax.bar(categories, values, color=color, edgecolor='none', linewidth=0)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
# 补丁级别,添加适应指定上下限
# ax.set_ylim(0, max(values) * y_lim)
if isinstance(y_lim, (tuple, list)):
ax.set_ylim(y_lim)
else:
ax.set_ylim(0, max(values) * y_lim)
if rotate_xticks:
ax.set_xticklabels(categories, rotation=rotate_xticks, ha="right")
if show_values:
ax.bar_label(bars, padding=2, fontsize=8)
plt.tight_layout()
if save_path is not None:
save_fig(save_path)
plt.close()