如何夸大 SVG 图的 Y 轴?

问题描述

在这个 SVG 图表中,线条太平了。如何夸大点的 Y 值差异,使其看起来更“锯齿形”,线的最低点位于图表底部,最高点位于顶部?

svg {
  display: flex;
  width: calc(100% + 4em);
  transform: translateX(-2em);
  clip-path: polygon(2em 0,calc(100% - 2em) 0,calc(100% - 2em) 100%,2em 100%);
}

polyline {
  transform: scaleY(-1);
}
<svg viewBox="0 -100 900 100" class="chart" style="height: 100vh; width: 100vw;">
          <defs>
            <marker id="red-circle" viewBox="0 0 10 10" refX="5" refY="5" orient="auto">
              <circle fill="red" cx="5" cy="5" r="5" />
            </marker>
          </defs>
          <polyline fill="#FEF9CC" stroke="#FED225" stroke-width="2" points="
              0,0
              100,23
              200,21
              300,20
              400,20
              500,23
              600,28
              700,30
              800,30
              900,30
              0,-99999
              0,0
             " marker-start="url(#red-circle)" marker-end="url(#red-circle)" marker-mid="url(#red-circle)" />
        </svg>

解决方法

我在 Reddit 上收到了公式 here。这是我的实现方式:

const exaggerate = function () {
  const polyline = document.querySelector('polyline');
  const points = [...polyline.points].slice(2,-2);
  // slice off (ignore) first 2 and last 2 because
  // they are purely for closing the loop
  // so that it can be filled with a color
  const ys = points.map(({ y }) => y);
  const y_min = Math.min(...ys);
  const y_max = Math.max(...ys);
  points.forEach((point) => {
    point.y = (point.y - y_min) * 100 / (y_max - y_min);
  });
}

exaggerate();
svg {
  display: flex;
  width: calc(100% + 4em);
  transform: translateX(-2em);
  clip-path: polygon(2em 0,calc(100% - 2em) 0,calc(100% - 2em) 100%,2em 100%);
}

polyline {
  transform: scaleY(-1);
}
<svg viewBox="0 -100 900 100" class="chart" style="height: 100vh; width: 100vw;">
          <defs>
            <marker id="red-circle" viewBox="0 0 10 10" refX="5" refY="5" orient="auto">
              <circle fill="red" cx="5" cy="5" r="5" />
            </marker>
    https://stackoverflow.com/questions/66473797/how-to-exaggerate-the-y-axis-of-an-svg-plot#      </defs>
          <polyline fill="#FEF9CC" stroke="#FED225" stroke-width="2" points="
              0,0
              100,23
              200,21
              300,20
              400,20
              500,23
              600,28
              700,30
              800,30
              900,30
              0,-99999
              0,0
             " marker-start="url(#red-circle)" marker-end="url(#red-circle)" marker-mid="url(#red-circle)" />
        </svg>

编辑:

也遇到了 this 个问题和答案,对于任何感兴趣的人。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...