三维分组渐变柱状图

来源与调用 · 完整代码

   1 """Three-dimensional grouped gradient bars, adapted from the supplied reproduction.
   2 Default demo heights were transcribed from the reference image; demo errors are
   3 illustrative only. Custom data never receives invented uncertainty.
   4 Run from a bootstrapped Vivid workspace, or directly from the installed catalog.
   5 """
   6 from pathlib import Path
   7 import argparse
   8 import csv
   9 import sys
  10 import numpy as np
  11 import matplotlib
  12 matplotlib.use('Agg')
  13 import matplotlib.pyplot as plt
  14 from matplotlib.colors import ListedColormap, BoundaryNorm, to_rgb, LinearSegmentedColormap
  15 from matplotlib.colorbar import ColorbarBase
  16 from matplotlib.ticker import MaxNLocator
  17 from mpl_toolkits.mplot3d.art3d import Poly3DCollection
  18 
  19 # Resolve the active workspace utilities or the installed skill's shared bundle.
  20 for base in (Path.cwd(), *Path.cwd().parents, *Path(__file__).resolve().parents):
  21     candidates = (base / '_utils', base / 'original/resources/assets/shared-scripts')
  22     found = next((p for p in candidates if (p / 'vivid_config.py').is_file()), None)
  23     if found is not None:
  24         sys.path.insert(0, str(found))
  25         break
  26 else:
  27     raise RuntimeError('Run Vivid bootstrap in the workspace before using this recipe.')
  28 from vivid_config import palette_colors
  29 from plot_utils import setup_style
  30 
  31 
  32 def read_matrix(path):
  33     """Wide CSV: first column row label, remaining column headers are conditions."""
  34     with Path(path).open(encoding='utf-8-sig', newline='') as stream:
  35         rows = list(csv.reader(stream))
  36     if len(rows) < 2 or len(rows[0]) < 2 or any(len(r) != len(rows[0]) for r in rows):
  37         raise ValueError('Expected a rectangular CSV with row and column labels.')
  38     labels, conditions = [r[0] for r in rows[1:]], rows[0][1:]
  39     if len(set(labels)) != len(labels) or len(set(conditions)) != len(conditions):
  40         raise ValueError('Row and column labels must be unique.')
  41     return np.array([[float(v) for v in r[1:]] for r in rows[1:]]), labels, conditions
  42 
  43 
  44 def plot_chart(values, samples, ss, *, errors=None, bounds=None,
  45                value_label='Value', sample_label='Sample', condition_label='Condition',
  46                note=None):
  47     """errors: nonnegative lengths shaped (rows, columns) or (2, rows, columns).
  48 
  49     A 2-D array gives symmetric errors; a 3-D array gives lower/upper lengths.
  50     None omits error marks. Heights and colorbar share the same explicit bins.
  51     """
  52     values = np.asarray(values, dtype=float)
  53     if (values.ndim != 2 or values.size == 0 or not np.isfinite(values).all()
  54             or (values < 0).any() or values.shape != (len(samples), len(ss))):
  55         raise ValueError('Expected finite nonnegative heights matching both label axes.')
  56     nrows, ncols = values.shape
  57     lower = upper = np.zeros_like(values)
  58     if errors is not None:
  59         error_array = np.asarray(errors, dtype=float)
  60         if error_array.shape == values.shape:
  61             lower = upper = error_array
  62         elif error_array.shape == (2, *values.shape):
  63             lower, upper = error_array
  64         else:
  65             raise ValueError('Error shape must match heights, optionally with lower/upper axis.')
  66         if (not np.isfinite(error_array).all() or (error_array < 0).any()
  67                 or (lower > values).any()):
  68             raise ValueError('Errors must be finite, nonnegative and not cross the zero base.')
  69     if bounds is None:
  70         # Linear bins for new data; original demo binning is supplied explicitly.
  71         bounds = np.linspace(0, max(float(values.max()), 1.0), 12)
  72     bounds = np.asarray(bounds, dtype=float)
  73     if (bounds.ndim != 1 or len(bounds) < 3 or not np.isfinite(bounds).all()
  74             or (np.diff(bounds) <= 0).any()
  75             or bounds[0] > values.min() or bounds[-1] < values.max()):
  76         raise ValueError('Increasing bin boundaries must cover every height.')
  77     setup_style()
  78     plt.rcParams.update({'font.family': 'serif', 'font.serif': ['Times New Roman', 'DejaVu Serif'],
  79                          'font.weight': 'bold', 'axes.labelweight': 'bold', 'font.size': 12,
  80                          'pdf.fonttype': 42, 'axes.linewidth': 1.2})
  81     # Numeric bins use the palette's raw ordered scale, not categorical ordering.
  82     scale = LinearSegmentedColormap.from_list('vivid_ordered', palette_colors())
  83     colors = scale(np.linspace(0, 1, len(bounds)-1))[:, :3]
  84     cmap = ListedColormap(colors)
  85     norm = BoundaryNorm(bounds, cmap.N, clip=True)
  86     fig = plt.figure(figsize=(14.4, 12.8), facecolor='white')
  87     ax = fig.add_axes([.015, .055, .81, .90], projection='3d', computed_zorder=False)
  88     ax.view_init(elev=27, azim=-56)
  89     ax.set_proj_type('ortho')
  90     ax.set_box_aspect((max(nrows * 1.1, 2), max(ncols * .955, 2), 8))
  91 
  92     # Side faces fade from near-white at the foot to the bin color at the top.
  93     label_offset = max(float((values + upper).max()), 1.0) * .02
  94     faces, facecolors = [], []
  95     w, d = .62, .62
  96     for i in range(nrows):
  97         for j in range(ncols):
  98             h = values[i,j]
  99             base = np.array(to_rgb(colors[int(norm(h))]))
 100             x0, x1, y0, y1 = i-w/2, i+w/2, j-d/2, j+d/2
 101             n = 40 if h > 1.5 else 1
 102             levels = np.linspace(0, h, n+1)
 103             for k in range(n):
 104                 z0, z1 = levels[k:k+2]
 105                 t = (k+.5)/n
 106                 c = base if h <= 1.5 else np.ones(3)*(1-t**.65)+base*t**.65
 107                 for points, shade in [([(x0,y0,z0),(x1,y0,z0),(x1,y0,z1),(x0,y0,z1)],.98),
 108                                       ([(x1,y0,z0),(x1,y1,z0),(x1,y1,z1),(x1,y0,z1)],.88),
 109                                       ([(x1,y1,z0),(x0,y1,z0),(x0,y1,z1),(x1,y1,z1)],.92),
 110                                       ([(x0,y1,z0),(x0,y0,z0),(x0,y0,z1),(x0,y1,z1)],1.)]:
 111                     faces.append(points)
 112                     facecolors.append(np.clip(c*shade,0,1))
 113             faces.append([(x0,y0,h),(x1,y0,h),(x1,y1,h),(x0,y1,h)])
 114             facecolors.append(np.clip(base*1.04,0,1))
 115     ax.add_collection3d(Poly3DCollection(faces, facecolors=facecolors, edgecolors='none',
 116                                         linewidths=0, antialiased=False, zsort='average', zorder=3))
 117     # Draw error marks only from the supplied symmetric/asymmetric error lengths.
 118     for i in range(nrows):
 119         for j in range(ncols):
 120             h = values[i,j]
 121             err = upper[i,j]
 122             if errors is not None:
 123                 ax.plot([i,i], [j,j], [h-lower[i,j],h+err], c='black', lw=1.25, zorder=5)
 124                 ax.plot([i-.10,i+.10], [j,j], [h+err,h+err], c='black', lw=1.25, zorder=5)
 125             ax.text(i, j, h+err+label_offset, f'{h:.2f}', ha='center', va='bottom',
 126                     fontsize=10, zorder=6, bbox=dict(facecolor='white', edgecolor='none', alpha=.87, pad=.15))
 127     ax.set(xlim=(-.65,nrows-.35), ylim=(-.65,ncols-.35),
 128            zlim=(0,max(float((values+upper).max()), 1.0) * 1.08))
 129     ax.set_xticks(range(nrows), samples, rotation=-15)
 130     ax.set_yticks(range(ncols), ss, rotation=18)
 131     ax.zaxis.set_major_locator(MaxNLocator(nbins=12))
 132     ax.set_xlabel(sample_label, labelpad=22, fontsize=19)
 133     ax.set_ylabel(condition_label, labelpad=24, fontsize=19)
 134     ax.set_zlabel(value_label, labelpad=20, fontsize=18)
 135     ax.zaxis._axinfo['juggled'] = (1,2,0)
 136     for axis in (ax.xaxis, ax.yaxis, ax.zaxis):
 137         axis.set_pane_color((1,1,1,1))
 138         axis.pane.set_edgecolor('black')
 139         axis._axinfo['grid'].update(color=(.68,.68,.68,1), linestyle='--', linewidth=.8)
 140     ax.tick_params(axis='both', labelsize=12, pad=3)
 141     cax = fig.add_axes([.865,.205,.024,.63])
 142     cb = ColorbarBase(cax, cmap=cmap, norm=norm, boundaries=bounds, ticks=bounds, spacing='uniform')
 143     cb.ax.set_yticklabels([f'{v:.3g}' for v in bounds])
 144     cb.ax.tick_params(labelsize=14, pad=6)
 145     cb.set_label(value_label, fontsize=18, labelpad=17)
 146     if note:
 147         fig.text(.05, .018, note, fontsize=11, color='#444444')
 148     return fig
 149 
 150 
 151 def main():
 152     parser = argparse.ArgumentParser(description=__doc__)
 153     parser.add_argument('--data', type=Path, help='Wide CSV of heights')
 154     parser.add_argument('--errors', type=Path, help='Wide CSV of symmetric error lengths, matching data labels')
 155     parser.add_argument('--output', type=Path, default=Path('figures/fig_grouped_bar_3d'))
 156     parser.add_argument('--value-label', default=None)
 157     args = parser.parse_args()
 158     if args.data:
 159         values, samples, conditions = read_matrix(args.data)
 160         errors = None
 161         if args.errors:
 162             errors, error_rows, error_cols = read_matrix(args.errors)
 163             if samples != error_rows or conditions != error_cols:
 164                 raise ValueError('Error CSV labels and order must match the data CSV.')
 165         fig = plot_chart(values, samples, conditions, errors=errors,
 166                          value_label=args.value_label or 'Value')
 167     else:
 168         if args.errors:
 169             parser.error('--errors requires --data')
 170         # Heights transcribed from the user reference. Errors are illustrative.
 171         samples = ['C-28', 'C-7', 'C-3', 'C-1', 'U-28', 'U-1']
 172         conditions = ['SS-0', 'SS-0.1', 'SS-0.2', 'SS-0.3', 'SS-0.4', 'SS-0.5', 'SS-0.6', 'SS-0.7', 'SS-0.8', 'SS-0.9', 'SS-1']
 173         values = np.array([[0.34, 3.95, 8.36, 13.81, 16.24, 23.39, 32.97, 35.36, 38.44, 46.64, 57.14], [0.33, 3.12, 7.98, 13.09, 14.75, 20.15, 28.26, 31.24, 35.76, 42.32, 55.28], [0.3, 3.01, 6.3, 12.16, 13.12, 18.45, 25.76, 28.29, 33.03, 37.68, 49.88], [0.28, 2.84, 5.48, 9.72, 11.09, 14.44, 22.31, 25.53, 30.48, 34.04, 36.08], [0.33, 2.77, 4.23, 5.52, 6.12, 7.29, 9.26, 10.76, 13.49, 14.24, 17.13], [0.21, 0.55, 0.71, 0.81, 1.12, 1.24, 2.59, 3.54, 3.86, 4.07, 6.31]])
 174         upper = np.maximum(.10, .025 * values)
 175         errors = np.stack([.35 * upper, upper])
 176         bounds = [.21, .35, .58, .97, 1.6, 2.7, 4.5, 7.4, 12.4, 20.6, 34.3, 57.14]
 177         fig = plot_chart(values, samples, conditions, errors=errors, bounds=bounds,
 178                          value_label=args.value_label or 'Compressive strength /MPa',
 179                          condition_label='SS Content',
 180                          note='Reference-label heights; illustrative error bars (not measured).')
 181     args.output.parent.mkdir(parents=True, exist_ok=True)
 182     for suffix in ('png', 'pdf'):
 183         fig.savefig(args.output.with_suffix('.' + suffix), dpi=300,
 184                     facecolor='white', bbox_inches='tight', pad_inches=.25)
 185     plt.close(fig)
 186     print('Saved PNG and PDF:', args.output)
 187 
 188 
 189 if __name__ == '__main__':
 190     main()