环形分组柱状对比图
来源与编码 · 完整源码
1 """Grouped radial bars with task labels and outer hierarchy arcs.
2
3 Reconstructed from a user-supplied reference image. The reference layout uses explicit within-task min/max scaling. Numeric labels
4 retain the supplied values; shared-scale mode is available for cross-task comparisons.
5 """
6 from pathlib import Path
7 import argparse
8 import csv
9 import sys
10 import textwrap
11
12 import numpy as np
13 import matplotlib
14 matplotlib.use('Agg')
15 import matplotlib.pyplot as plt
16 from matplotlib.colors import to_rgb
17 from matplotlib.patches import Patch
18
19 for base in (Path.cwd(), *Path.cwd().parents, *Path(__file__).resolve().parents):
20 found = next((p for p in (base / '_utils', base / 'original/resources/assets/shared-scripts')
21 if (p / 'vivid_config.py').is_file()), None)
22 if found is not None:
23 sys.path.insert(0, str(found))
24 break
25 else:
26 raise RuntimeError('Run Vivid bootstrap in the workspace before using this recipe.')
27 from plot_utils import PALETTE, COLORS, setup_style
28
29
30 def _labels(items, name, count=None, unique=False, allow_empty=False):
31 if isinstance(items, (str, bytes)):
32 raise ValueError(f'{name} must be a list of labels.')
33 labels = [str(item).strip() for item in items]
34 if count is not None and len(labels) != count:
35 raise ValueError(f'{name} must contain {count} labels.')
36 if not allow_empty and any(not label for label in labels):
37 raise ValueError(f'{name} labels must be nonempty.')
38 if unique and len(set(labels)) != len(labels):
39 raise ValueError(f'{name} labels must be unique.')
40 return labels
41
42
43 def validate_data(task_names, model_names, values, major_groups=None, task_details=None,
44 highlight_index=0):
45 tasks = _labels(task_names, 'Task', unique=True)
46 models = _labels(model_names, 'Model', unique=True)
47 if not 2 <= len(tasks) <= 16 or not 2 <= len(models) <= 8:
48 raise ValueError('Use 2–16 tasks and 2–8 models.')
49 if len(tasks) * len(models) > 96:
50 raise ValueError('At most 96 bars are supported; split a larger comparison into panels.')
51 data = np.asarray(values, dtype=float)
52 if data.shape != (len(tasks), len(models)):
53 raise ValueError('Values must have shape (number of tasks, number of models).')
54 if not np.isfinite(data).all() or (data < 0).any():
55 raise ValueError('Values must be finite and nonnegative; missing values are not zero.')
56 if not isinstance(highlight_index, (int, np.integer)) or not 0 <= highlight_index < len(models):
57 raise ValueError('highlight_index must identify an existing model column.')
58 groups = None if major_groups is None else _labels(major_groups, 'Major group', len(tasks))
59 if groups is not None:
60 runs = [group for i, group in enumerate(groups) if i == 0 or group != groups[i-1]]
61 if len(runs) != len(set(runs)):
62 raise ValueError('Tasks in the same major group must be contiguous; input order is preserved.')
63 details = ([''] * len(tasks) if task_details is None else
64 _labels(task_details, 'Task detail', len(tasks), allow_empty=True))
65 return tasks, models, data, groups, details
66
67
68 def _upright(rotation):
69 """Return an equivalent text rotation that is never upside down."""
70 return (rotation + 90) % 180 - 90
71
72
73 def _model_styles(count, highlight_index, background):
74 """Derive one emphasis color and a four-step comparison tint from the palette."""
75 highlight = PALETTE[1 % len(PALETTE)]
76 base = np.array(to_rgb(PALETTE[0]))
77 pale = np.array(to_rgb(background))
78 colors = [None] * count
79 colors[highlight_index] = highlight
80 comparison = [i for i in range(count) if i != highlight_index]
81 for position, column in enumerate(comparison):
82 mix = 0.0 if len(comparison) == 1 else .58 * position / (len(comparison) - 1)
83 colors[column] = tuple(base * (1 - mix) + pale * mix)
84 return colors
85
86
87 def _layout_angles(task_count, model_count, groups, highlight_index):
88 """Wider emphasis bars, small task gaps and larger hierarchy gaps."""
89 widths = np.ones(model_count)
90 widths[highlight_index] = 1.8
91 bar_gap, task_gap, hierarchy_gap = .175, 1.1, 3.3
92 span = widths.sum() + bar_gap * (model_count - 1)
93 boundary = [groups is not None and groups[i] != groups[(i + 1) % task_count]
94 for i in range(task_count)]
95 gaps = np.array([hierarchy_gap if major else task_gap for major in boundary])
96 factor = 2 * np.pi / (task_count * span + gaps.sum())
97 cursor = gaps[-1] / 2
98 task_centers, angles, starts, ends = [], [], [], []
99 for i in range(task_count):
100 starts.append(cursor * factor)
101 task_centers.append((cursor + span / 2) * factor)
102 row = []
103 for j, width in enumerate(widths):
104 row.append((cursor + width / 2) * factor)
105 cursor += width + (bar_gap if j < model_count - 1 else 0)
106 angles.append(row)
107 ends.append(cursor * factor)
108 cursor += gaps[i]
109 return np.asarray(angles), np.asarray(task_centers), widths * factor, starts, ends
110
111
112 def plot_chart(task_names, model_names, values, major_groups=None, task_details=None,
113 center_label='方案对比', highlight_index=0, *, value_format='.2f',
114 value_suffix='', show_values=True, show_legend=True, scale_max=None,
115 scale_mode='within_task', baseline_label=None):
116 """Reproduce the reference composition without silently changing data semantics.
117
118 within_task: each task maps its minimum/maximum to radial lengths 100/300.
119 Equal values use length 200. The visible values always remain the originals.
120 shared: lengths are 300 * value / scale_max, with one zero baseline.
121 Input row/column order is preserved. Highlighting does not imply first place.
122 """
123 tasks, models, data, groups, details = validate_data(
124 task_names, model_names, values, major_groups, task_details, highlight_index)
125 setup_style()
126 maximum = float(data.max())
127 scale = maximum if scale_max is None else float(scale_max)
128 if scale_max is not None and (not np.isfinite(scale) or scale <= 0 or scale < maximum):
129 raise ValueError('scale_max must be finite, positive, and cover all values.')
130 if scale_mode not in ('within_task', 'shared'):
131 raise ValueError("scale_mode must be 'within_task' or 'shared'.")
132 if scale_mode == 'within_task' and scale_max is not None:
133 raise ValueError('scale_max applies only to shared-scale mode.')
134 if scale_mode == 'within_task':
135 minima = data.min(axis=1, keepdims=True)
136 ranges = np.ptp(data, axis=1, keepdims=True)
137 relative = np.divide(data - minima, ranges, out=np.full_like(data, .5), where=ranges != 0)
138 lengths = 100 + 200 * relative
139 else:
140 lengths = 300 * data / (scale if scale > 0 else 1)
141 format(0.0, value_format)
142 ntasks, nmodels = data.shape
143 dense = ntasks * nmodels > 64
144 background = '#FFFFFF'
145 ink, arc_color = '#725E4D', '#BFB19E'
146 from matplotlib.font_manager import fontManager
147 available = {font.name for font in fontManager.ttflist}
148 fonts = [name for name in ('Times New Roman', 'DejaVu Serif', 'Microsoft YaHei',
149 'Noto Sans CJK SC', 'WenQuanYi Zen Hei') if name in available]
150 # Pixel-equivalent reference geometry: 1331 x 1252, center (660, 653), R=570.
151 factor = 1.12 if dense else 1.0
152 fig = plt.figure(figsize=(13.31 * factor, 12.52 * factor), facecolor=background)
153 ax = fig.add_axes([40 / 1331, -21 / 1252, 1240 / 1331, 1240 / 1252], projection='polar')
154 ax.set_facecolor(background)
155 ax.set_theta_zero_location('N')
156 ax.set_theta_direction(-1)
157 angles, centers, widths, starts, ends = _layout_angles(ntasks, nmodels, groups, highlight_index)
158 colors = _model_styles(nmodels, highlight_index, background)
159 bottom = 165.0
160 label_size = 8.5 if dense else 10.2
161 comparison = [i for i in range(nmodels) if i != highlight_index]
162 for task in range(ntasks):
163 for model in range(nmodels):
164 angle, length, color = angles[task, model], lengths[task, model], colors[model]
165 ax.bar(angle, length, width=widths[model], bottom=bottom, color=color,
166 edgecolor='none', linewidth=0, zorder=3)
167 if show_values:
168 rotation = _upright(90 - np.degrees(angle))
169 outward_right = np.cos(np.radians(rotation) - (np.pi / 2 - angle)) > 0
170 inside = length >= 75
171 radius = bottom + length - 13 if inside else bottom + length + 6
172 alignment = ('right' if outward_right else 'left') if inside else (
173 'left' if outward_right else 'right')
174 text_color = ('white' if model in (highlight_index, comparison[0]) else ink) if inside else ink
175 ax.text(angle, radius, f'{data[task, model]:{value_format}}{value_suffix}',
176 rotation=rotation, rotation_mode='anchor', ha=alignment, va='center',
177 fontsize=label_size, fontfamily=fonts, fontweight='bold', color=text_color, zorder=6)
178 wrap_width = max(12, int(240 / ntasks))
179 for angle, task, detail in zip(centers, tasks, details):
180 rotation = _upright(-np.degrees(angle))
181 lower_half = np.cos(angle) < 0
182 task_radius, detail_radius = (500, 535) if lower_half else (535, 500)
183 ax.text(angle, task_radius, textwrap.fill(task, width=wrap_width), ha='center', va='center',
184 rotation=rotation, rotation_mode='anchor', fontfamily=fonts,
185 fontsize=14 if dense else 17, fontweight='bold', color=ink, zorder=7)
186 if detail:
187 detail_font = min(10 if dense else 12.3, 445 / max(30, len(detail)))
188 ax.text(angle, detail_radius, detail,
189 ha='center', va='center', rotation=rotation, rotation_mode='anchor',
190 fontfamily=fonts, fontsize=detail_font, color=ink, zorder=7)
191 if groups is not None:
192 start = 0
193 for end in range(1, ntasks + 1):
194 if end == ntasks or groups[end] != groups[start]:
195 first, last = starts[start] - .035, ends[end - 1] + .035
196 theta = np.linspace(first, last, max(32, (end - start) * 40))
197 ax.plot(theta, np.full_like(theta, 570), color=arc_color, linewidth=2.5, zorder=1)
198 middle = (first + last) / 2
199 if middle > 1.5 * np.pi and len(groups[start]) > 18:
200 middle = last - .30 * (last - first)
201 # A long group title follows its tangent, exactly as the reference.
202 ax.text(middle, 593, groups[start], ha='center', va='center',
203 rotation=_upright(-np.degrees(middle)), rotation_mode='anchor',
204 fontfamily=fonts, fontsize=16 if dense else 19,
205 fontweight='bold', color='#A18E7B', zorder=8)
206 start = end
207 title = str(center_label)
208 title = textwrap.fill(title, width=18) if len(title) > 18 and '\n' not in title else title
209 import unicodedata
210 longest = max((sum(2 if unicodedata.east_asian_width(char) in ('W', 'F') else 1
211 for char in line) for line in title.splitlines()), default=0)
212 fontsize = min(35.5, 35.5 * 11 / max(1, longest))
213 ax.text(.5, .5, title, transform=ax.transAxes, ha='center', va='center',
214 fontsize=fontsize, fontfamily=fonts, fontweight='bold', color=colors[highlight_index], zorder=9)
215 ax.set_ylim(0, 620)
216 ax.set_xticks([])
217 ax.set_yticks([])
218 ax.grid(False)
219 ax.spines['polar'].set_visible(False)
220 if show_legend:
221 if baseline_label is not None:
222 from matplotlib.legend_handler import HandlerTuple
223 class TopAlignedTuple(HandlerTuple):
224 def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans):
225 items = super().create_artists(legend, orig_handle, xdescent, ydescent,
226 width, height, fontsize, trans)
227 offset = max(0, len(str(baseline_label).splitlines()) - 1) * fontsize * .60
228 for item in items:
229 item.set_y(item.get_y() + offset)
230 return items
231 handles = [Patch(facecolor=colors[highlight_index], edgecolor='none'),
232 tuple(Patch(facecolor=colors[i], edgecolor='none') for i in comparison)]
233 labels = [models[highlight_index], baseline_label]
234 legend = fig.legend(handles, labels, handler_map={tuple: TopAlignedTuple(ndivide=None, pad=.10)},
235 loc='upper left', bbox_to_anchor=(.012, .981), borderaxespad=0,
236 frameon=False, fontsize=15.8, handlelength=1.15,
237 handleheight=1.0, labelspacing=.35, handletextpad=.6)
238 else:
239 handles = [Patch(facecolor=color, edgecolor='none', label=name)
240 for name, color in zip(models, colors)]
241 legend = fig.legend(handles=handles, loc='upper left', bbox_to_anchor=(.012, .981),
242 borderaxespad=0, frameon=False, fontsize=12.0 if nmodels > 5 else 14.0,
243 handlelength=1.15, handleheight=1.0, labelspacing=.25)
244 for text in legend.get_texts():
245 text.set_fontfamily(fonts)
246 text.set_color(ink)
247 return fig
248
249
250 def read_wide_csv(path):
251 """Read task names followed by model value columns, preserving table order."""
252 with Path(path).open(encoding='utf-8-sig', newline='') as stream:
253 rows = list(csv.reader(stream))
254 if len(rows) < 3 or len(rows[0]) < 3 or any(len(row) != len(rows[0]) for row in rows):
255 raise ValueError('CSV must be rectangular: task plus 2–8 model columns, at least 2 tasks.')
256 tasks = [row[0].strip() for row in rows[1:]]
257 models = [cell.strip() for cell in rows[0][1:]]
258 values = np.array([[float(cell) for cell in row[1:]] for row in rows[1:]])
259 validate_data(tasks, models, values)
260 return tasks, models, values
261
262
263 def read_metadata_csv(path, task_names):
264 """Join task/group/detail metadata by name; never silently reorder task data."""
265 with Path(path).open(encoding='utf-8-sig', newline='') as stream:
266 rows = list(csv.reader(stream))
267 if len(rows) < 2 or len(rows[0]) != 3 or any(len(row) != 3 for row in rows):
268 raise ValueError('Metadata CSV requires three columns: task, major group, short detail.')
269 by_task = {}
270 for task, group, detail in rows[1:]:
271 task = task.strip()
272 if task in by_task:
273 raise ValueError(f'Duplicate metadata task: {task}')
274 by_task[task] = (group.strip(), detail.strip())
275 if set(by_task) != set(task_names):
276 raise ValueError('Metadata tasks must match the data tasks exactly.')
277 return [by_task[task][0] for task in task_names], [by_task[task][1] for task in task_names]
278
279
280 def demo_data():
281 """Values transcribed from the reference image; not independently verified."""
282 return dict(
283 task_names=['Visual Prompt', 'Grounding', 'Dense', 'Referring', 'Robo Point',
284 'Referring Point', 'Grounding Point', 'Dense Point', 'GUI', 'OCR', 'Layout'],
285 model_names=['GroundingPI', 'Top 1 baseline', 'Top 2 baseline', 'Top 3 baseline', 'Top 4 baseline'],
286 values=np.array([[73.59, 65.84, 56.52, 54.85, 43.26], [59.50, 58.86, 58.03, 56.80, 56.59],
287 [57.48, 55.24, 51.17, 51.08, 40.98], [84.89, 82.52, 79.02, 78.56, 78.31],
288 [75.12, 81.08, 66.61, 65.39, 63.33], [89.71, 85.51, 84.56, 82.29, 79.96],
289 [82.15, 79.66, 74.89, 70.94, 70.83], [74.37, 76.10, 70.54, 70.26, 67.69],
290 [78.92, 92.58, 77.73, 72.24, 70.09], [54.79, 48.89, 47.34, 45.20, 43.30],
291 [79.95, 74.27, 71.64, 69.06, 61.50]]),
292 major_groups=['Bounding Boxes'] * 4 + ['Point'] * 5 + ['Text & Bounding Boxes'] * 2,
293 task_details=['FSC147-test, Dense200, COCO, LVIS', 'COCO, LVIS', 'Dense200, VisDrone',
294 'HumanRef, RefCOCOg*5', 'RoboSpatial, RefSpatial*3', 'HumanRef, RefCOCOg*5',
295 'COCO, LVIS', 'Dense200, VisDrone', 'Screenspot-Pro, ScreenSpot-V2, OSWorld-G',
296 'HierText, ICDAR2015, TotalText, SROIE', 'DocLayNet, M6Doc'],
297 center_label='GroundingPI',
298 baseline_label='Best Four models\nAcross 45 Baselines\nIncluding GPT-6 Astra')
299
300
301 def main():
302 parser = argparse.ArgumentParser(description=__doc__)
303 parser.add_argument('--data', type=Path, help='Wide CSV: task followed by model columns')
304 parser.add_argument('--metadata', type=Path, help='CSV columns: task, major group, short detail')
305 parser.add_argument('--output', type=Path, default=Path('figures/fig_grouped_radial_bar'))
306 parser.add_argument('--center-label', default=None)
307 parser.add_argument('--highlight-index', type=int, default=0)
308 parser.add_argument('--format', default='.2f')
309 parser.add_argument('--suffix', default='')
310 parser.add_argument('--scale-max', type=float)
311 parser.add_argument('--scale-mode', choices=['within_task', 'shared'], default='within_task')
312 parser.add_argument('--baseline-label', default=None)
313 parser.add_argument('--hide-values', action='store_true')
314 parser.add_argument('--hide-legend', action='store_true')
315 args = parser.parse_args()
316 if args.metadata and not args.data:
317 parser.error('--metadata requires --data')
318 if args.data:
319 tasks, models, values = read_wide_csv(args.data)
320 data = dict(task_names=tasks, model_names=models, values=values)
321 if args.metadata:
322 data['major_groups'], data['task_details'] = read_metadata_csv(args.metadata, tasks)
323 else:
324 data = demo_data()
325 if args.center_label is not None:
326 data['center_label'] = args.center_label
327 if args.baseline_label is not None:
328 data['baseline_label'] = args.baseline_label
329 fig = plot_chart(**data, highlight_index=args.highlight_index, value_format=args.format,
330 value_suffix=args.suffix, scale_max=args.scale_max, scale_mode=args.scale_mode,
331 show_values=not args.hide_values, show_legend=not args.hide_legend)
332 args.output.parent.mkdir(parents=True, exist_ok=True)
333 for extension in ('png', 'pdf', 'svg'):
334 fig.savefig(args.output.with_suffix('.' + extension), dpi=200, facecolor=fig.get_facecolor(),
335 bbox_inches=None, pad_inches=0)
336 plt.close(fig)
337 print('Saved PNG, PDF and SVG:', args.output)
338
339
340 if __name__ == '__main__':
341 main()