Combo-диаграммы: столбцы+линия на вторичной оси #60
+282
-56
@@ -26,6 +26,9 @@ final class CartesianPainter {
|
|||||||
ChartSpec.AxisSpec valAxis = spec.valAxis != null ? spec.valAxis : new ChartSpec.AxisSpec();
|
ChartSpec.AxisSpec valAxis = spec.valAxis != null ? spec.valAxis : new ChartSpec.AxisSpec();
|
||||||
ChartSpec.AxisSpec catAxis = spec.catAxis != null ? spec.catAxis : new ChartSpec.AxisSpec();
|
ChartSpec.AxisSpec catAxis = spec.catAxis != null ? spec.catAxis : new ChartSpec.AxisSpec();
|
||||||
boolean catReversed = catAxis.reversed;
|
boolean catReversed = catAxis.reversed;
|
||||||
|
// Вторичная ось значений (combo, §21.2.2.145) — только вертикальные диаграммы:
|
||||||
|
// горизонтальных combo Word не порождает.
|
||||||
|
ChartSpec.AxisSpec secAxis = !horizontal ? spec.secondaryValAxis : null;
|
||||||
|
|
||||||
int nCat = 0;
|
int nCat = 0;
|
||||||
for (ChartSpec.Series s : spec.series) {
|
for (ChartSpec.Series s : spec.series) {
|
||||||
@@ -36,20 +39,80 @@ final class CartesianPainter {
|
|||||||
}
|
}
|
||||||
List<String> cats = categoriesOf(spec, nCat);
|
List<String> cats = categoriesOf(spec, nCat);
|
||||||
|
|
||||||
|
// §21.2.2.145: каждый ряд рисуется своим семейством (combo: столбцы + линия),
|
||||||
|
// не-combo ряды — по spec.type.
|
||||||
|
List<Integer> barIdx = new ArrayList<>();
|
||||||
|
List<Integer> lineIdx = new ArrayList<>();
|
||||||
|
List<Integer> areaIdx = new ArrayList<>();
|
||||||
|
for (int si = 0; si < spec.series.size(); si++) {
|
||||||
|
switch (familyOf(spec.series.get(si), spec.type)) {
|
||||||
|
case BAR -> barIdx.add(si);
|
||||||
|
case LINE -> lineIdx.add(si);
|
||||||
|
case AREA -> areaIdx.add(si);
|
||||||
|
default -> {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// §21.2.2.76 + §21.2.3.17: stacked — ряд на накопленной сумме предыдущих;
|
// §21.2.2.76 + §21.2.3.17: stacked — ряд на накопленной сумме предыдущих;
|
||||||
// percentStacked — суммы категорий нормируются к 100. LINE и 2-D bar (обе
|
// percentStacked — суммы категорий нормируются к 100. Накопление — внутри
|
||||||
// ориентации); 2-D AREA grouping не читает (не запрошено).
|
// семейства ряда (c:grouping его группы); 2-D AREA grouping не читает (не запрошено).
|
||||||
boolean stacked = (spec.type == ChartSpec.Type.LINE
|
String barGrouping = firstGrouping(spec, barIdx);
|
||||||
|| spec.type == ChartSpec.Type.BAR
|
boolean barStacked = !barIdx.isEmpty() && ChartRenderer.isStacked(barGrouping);
|
||||||
|| spec.type == ChartSpec.Type.BAR_HORIZONTAL)
|
double[][] barCum = barStacked
|
||||||
&& ChartRenderer.isStacked(spec.grouping);
|
? ChartRenderer.stackedCumulative(spec, barIdx,
|
||||||
boolean percent = stacked && "percentStacked".equalsIgnoreCase(spec.grouping);
|
"percentStacked".equalsIgnoreCase(barGrouping))
|
||||||
double[][] cum = stacked ? ChartRenderer.stackedCumulative(spec, percent) : null;
|
: null;
|
||||||
double[] range = stacked ? ChartRenderer.stackedRange(cum) : ChartRenderer.valueRange(spec);
|
String lineGrouping = firstGrouping(spec, lineIdx);
|
||||||
|
boolean lineStacked = !lineIdx.isEmpty() && ChartRenderer.isStacked(lineGrouping);
|
||||||
|
double[][] lineCum = lineStacked
|
||||||
|
? ChartRenderer.stackedCumulative(spec, lineIdx,
|
||||||
|
"percentStacked".equalsIgnoreCase(lineGrouping))
|
||||||
|
: null;
|
||||||
|
|
||||||
|
// Разделение серий по осям значений: ссылочное равенство с secondaryValAxis
|
||||||
|
// (назначается ChartSpec.parse по c:axId, §21.2.2.9).
|
||||||
|
List<Integer> primIdx = new ArrayList<>();
|
||||||
|
List<Integer> secIdx = new ArrayList<>();
|
||||||
|
for (int si = 0; si < spec.series.size(); si++) {
|
||||||
|
if (secAxis != null && spec.series.get(si).valAxis == secAxis) {
|
||||||
|
secIdx.add(si);
|
||||||
|
} else {
|
||||||
|
primIdx.add(si);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
List<Integer> barPrim = intersect(barIdx, primIdx);
|
||||||
|
List<Integer> linePrim = intersect(lineIdx, primIdx);
|
||||||
|
List<Integer> areaPrim = intersect(areaIdx, primIdx);
|
||||||
|
double[] barRange = null;
|
||||||
|
if (!barPrim.isEmpty()) {
|
||||||
|
barRange = barStacked ? cumRange(barCum, barIdx, primIdx)
|
||||||
|
: ChartRenderer.valueRange(spec, barPrim);
|
||||||
|
}
|
||||||
|
double[] lineRange = null;
|
||||||
|
if (!linePrim.isEmpty()) {
|
||||||
|
lineRange = lineStacked ? cumRange(lineCum, lineIdx, primIdx)
|
||||||
|
: ChartRenderer.valueRange(spec, linePrim);
|
||||||
|
}
|
||||||
|
double[] areaRange = areaPrim.isEmpty() ? null
|
||||||
|
: ChartRenderer.valueRange(spec, areaPrim);
|
||||||
|
double[] range = mergeRanges(barRange, lineRange, areaRange);
|
||||||
double[] bounds = ChartRenderer.axisBounds(valAxis, range[0], range[1], true);
|
double[] bounds = ChartRenderer.axisBounds(valAxis, range[0], range[1], true);
|
||||||
double lo = bounds[0];
|
double lo = bounds[0];
|
||||||
double hi = bounds[1];
|
double hi = bounds[1];
|
||||||
double unit = bounds[2];
|
double unit = bounds[2];
|
||||||
|
// Вторичная ось никогда не stacked (Word таких combo не пишет): сырой диапазон.
|
||||||
|
double secLo = 0;
|
||||||
|
double secHi = 1;
|
||||||
|
double secUnit = 1;
|
||||||
|
double[] secRange = null;
|
||||||
|
if (secAxis != null) {
|
||||||
|
secRange = ChartRenderer.valueRange(spec, secIdx);
|
||||||
|
double[] sb = ChartRenderer.axisBounds(secAxis, secRange[0], secRange[1], true);
|
||||||
|
secLo = sb[0];
|
||||||
|
secHi = sb[1];
|
||||||
|
secUnit = sb[2];
|
||||||
|
}
|
||||||
|
|
||||||
DrawMlText.Style valStyle = valAxis.labelStyle;
|
DrawMlText.Style valStyle = valAxis.labelStyle;
|
||||||
DrawMlText.Style catStyle = catAxis.labelStyle;
|
DrawMlText.Style catStyle = catAxis.labelStyle;
|
||||||
@@ -74,20 +137,18 @@ final class CartesianPainter {
|
|||||||
}
|
}
|
||||||
catLabelGutter += 8;
|
catLabelGutter += 8;
|
||||||
|
|
||||||
// Word укрупняет шаг оси значений, если подписи не влезают: интервал
|
// Word укрупняет шаг оси значений, если подписи не влезают (fitUnit) —
|
||||||
// между делениями не меньше ~2,5 высоты строки подписи. В word-export.pdf
|
// для обеих осей значений по одной и той же длине оси.
|
||||||
// у line chart (область ~71 pt, подписи 9 pt) шаг вышел 2 (0…6),
|
double axisLen = Math.max(10,
|
||||||
// а не 1 (0…5). Явные c:majorUnit/c:max не трогаем.
|
horizontal ? box.getWidth() - catLabelGutter : box.getHeight() - catGutter);
|
||||||
if (valStyle != null && !valAxis.deleted
|
double[] fit = fitUnit(valAxis, lo, hi, unit, range[0], range[1], axisLen);
|
||||||
&& valAxis.majorUnit == null && valAxis.max == null) {
|
hi = fit[0];
|
||||||
double labelH = DrawMlText.textHeight(valStyle);
|
unit = fit[1];
|
||||||
double axisLen = Math.max(10,
|
if (secAxis != null) {
|
||||||
horizontal ? box.getWidth() - catLabelGutter : box.getHeight() - catGutter);
|
double[] sfit = fitUnit(secAxis, secLo, secHi, secUnit,
|
||||||
while (hi - lo > unit && axisLen / ((hi - lo) / unit) < 2.5 * labelH) {
|
secRange[0], secRange[1], axisLen);
|
||||||
unit = ChartRenderer.nextUnit(unit);
|
secHi = sfit[0];
|
||||||
double top = range[1] + (range[1] - range[0]) / 20.0;
|
secUnit = sfit[1];
|
||||||
hi = Math.max(lo + unit, Math.ceil(top / unit - 1e-9) * unit);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
List<String> valLabels = new ArrayList<>();
|
List<String> valLabels = new ArrayList<>();
|
||||||
@@ -105,6 +166,18 @@ final class CartesianPainter {
|
|||||||
}
|
}
|
||||||
valGutter += 8; // auto-layout Word: отступ от подписей до области (Word-эмпирика)
|
valGutter += 8; // auto-layout Word: отступ от подписей до области (Word-эмпирика)
|
||||||
|
|
||||||
|
List<String> secLabels = new ArrayList<>();
|
||||||
|
double secGutter = 0;
|
||||||
|
if (secAxis != null && secAxis.labelStyle != null) {
|
||||||
|
for (double v = secLo; v <= secHi + secUnit / 2; v += secUnit) {
|
||||||
|
secLabels.add(ChartRenderer.formatValue(v, secAxis.numFmt));
|
||||||
|
}
|
||||||
|
for (String l : secLabels) {
|
||||||
|
secGutter = Math.max(secGutter, DrawMlText.textWidth(l, secAxis.labelStyle));
|
||||||
|
}
|
||||||
|
secGutter += 8;
|
||||||
|
}
|
||||||
|
|
||||||
// Горизонтальный: сверху подписи значений — резерв по высоте строки.
|
// Горизонтальный: сверху подписи значений — резерв по высоте строки.
|
||||||
// Guard valStyle != null — регрессия CartesianPainterTest#nullValAxisSkipsValueLabels.
|
// Guard valStyle != null — регрессия CartesianPainterTest#nullValAxisSkipsValueLabels.
|
||||||
double topGutter = (valStyle != null ? DrawMlText.textHeight(valStyle) : 0) + 6;
|
double topGutter = (valStyle != null ? DrawMlText.textHeight(valStyle) : 0) + 6;
|
||||||
@@ -114,10 +187,10 @@ final class CartesianPainter {
|
|||||||
Math.max(10, box.getWidth() - catLabelGutter),
|
Math.max(10, box.getWidth() - catLabelGutter),
|
||||||
Math.max(10, box.getHeight() - topGutter))
|
Math.max(10, box.getHeight() - topGutter))
|
||||||
: new Rectangle2D.Double(box.getX() + valGutter, box.getY(),
|
: new Rectangle2D.Double(box.getX() + valGutter, box.getY(),
|
||||||
Math.max(10, box.getWidth() - valGutter),
|
Math.max(10, box.getWidth() - valGutter - secGutter),
|
||||||
Math.max(10, box.getHeight() - catGutter));
|
Math.max(10, box.getHeight() - catGutter));
|
||||||
|
|
||||||
// 2. Сетка по делениям оси значений
|
// 2. Сетка по делениям оси значений (первичной; вторичной — только когда заявлена).
|
||||||
if (valAxis.gridlines && !valAxis.deleted) {
|
if (valAxis.gridlines && !valAxis.deleted) {
|
||||||
g.setColor(valAxis.gridColor);
|
g.setColor(valAxis.gridColor);
|
||||||
g.setStroke(new BasicStroke(0.6f));
|
g.setStroke(new BasicStroke(0.6f));
|
||||||
@@ -134,17 +207,25 @@ final class CartesianPainter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (secAxis != null && secAxis.gridlines && !secAxis.deleted) {
|
||||||
// 3. Ряды
|
g.setColor(secAxis.gridColor);
|
||||||
switch (spec.type) {
|
g.setStroke(new BasicStroke(0.6f));
|
||||||
case LINE -> drawLines(g, spec, plot, palette, lo, hi, nCat, horizontal, catReversed, cum);
|
for (double v = secLo; v <= secHi + secUnit / 2; v += secUnit) {
|
||||||
case AREA -> drawAreas(g, spec, plot, palette, lo, hi, nCat, horizontal, catReversed);
|
double t = (v - secLo) / (secHi - secLo);
|
||||||
case BAR, BAR_HORIZONTAL -> drawBars(g, spec, plot, palette, lo, hi, nCat,
|
double y = plot.getY() + (1 - t) * plot.getHeight();
|
||||||
horizontal, catReversed, cum);
|
g.draw(new java.awt.geom.Line2D.Double(plot.getX(), y,
|
||||||
default -> {
|
plot.getX() + plot.getWidth(), y));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 3. Ряды — фиксированный порядок семейств: столбцы позади, линия поверх (как Word).
|
||||||
|
drawBars(g, spec, plot, palette, lo, hi, secLo, secHi, barIdx, nCat,
|
||||||
|
horizontal, catReversed, barCum);
|
||||||
|
drawAreas(g, spec, plot, palette, lo, hi, secLo, secHi, areaIdx, nCat,
|
||||||
|
horizontal, catReversed);
|
||||||
|
drawLines(g, spec, plot, palette, lo, hi, secLo, secHi, lineIdx, nCat,
|
||||||
|
horizontal, catReversed, lineCum);
|
||||||
|
|
||||||
// 4. Линия категории и подписи
|
// 4. Линия категории и подписи
|
||||||
if (catAxis.axisLineColor != null && !catAxis.deleted) {
|
if (catAxis.axisLineColor != null && !catAxis.deleted) {
|
||||||
g.setColor(catAxis.axisLineColor);
|
g.setColor(catAxis.axisLineColor);
|
||||||
@@ -160,6 +241,110 @@ final class CartesianPainter {
|
|||||||
}
|
}
|
||||||
drawCategoryLabels(g, cats, plot, catStyle, horizontal, catReversed);
|
drawCategoryLabels(g, cats, plot, catStyle, horizontal, catReversed);
|
||||||
drawValueLabels(g, valLabels, plot, valStyle, lo, hi, horizontal);
|
drawValueLabels(g, valLabels, plot, valStyle, lo, hi, horizontal);
|
||||||
|
|
||||||
|
// 5. Вторичная ось значений: линия по правому краю области + подписи справа
|
||||||
|
// (§21.2.2.226, c:axPos="r"). Регрессия — CartesianPainterTest#combo_barsAndLineOnSecondary_bothDrawn.
|
||||||
|
if (secAxis != null && !secAxis.deleted) {
|
||||||
|
if (secAxis.axisLineColor != null) {
|
||||||
|
g.setColor(secAxis.axisLineColor);
|
||||||
|
g.setStroke(new BasicStroke((float) Math.max(0.5, secAxis.axisLineWidth)));
|
||||||
|
g.draw(new java.awt.geom.Line2D.Double(plot.getMaxX(), plot.getY(),
|
||||||
|
plot.getMaxX(), plot.getMaxY()));
|
||||||
|
}
|
||||||
|
drawSecondaryValueLabels(g, secLabels, plot, secAxis.labelStyle, secLo, secHi);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Семейство отрисовки ряда: renderAs (combo, §21.2.2.145), иначе — по spec.type. */
|
||||||
|
private static ChartSpec.Type familyOf(ChartSpec.Series s, ChartSpec.Type type) {
|
||||||
|
if (s.renderAs != null) {
|
||||||
|
return s.renderAs == ChartSpec.Type.BAR_HORIZONTAL
|
||||||
|
? ChartSpec.Type.BAR : s.renderAs;
|
||||||
|
}
|
||||||
|
return switch (type) {
|
||||||
|
case BAR, BAR_HORIZONTAL -> ChartSpec.Type.BAR;
|
||||||
|
case LINE -> ChartSpec.Type.LINE;
|
||||||
|
case AREA -> ChartSpec.Type.AREA;
|
||||||
|
default -> ChartSpec.Type.UNSUPPORTED;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** c:grouping первой серии семейства (null → spec.grouping). */
|
||||||
|
private static String firstGrouping(ChartSpec spec, List<Integer> idx) {
|
||||||
|
if (idx.isEmpty()) {
|
||||||
|
return spec.grouping;
|
||||||
|
}
|
||||||
|
String gr = spec.series.get(idx.get(0)).grouping;
|
||||||
|
return gr != null ? gr : spec.grouping;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Серия на вторичной оси значений (ссылочное равенство с secondaryValAxis). */
|
||||||
|
private static boolean onSecondary(ChartSpec.Series s, ChartSpec spec) {
|
||||||
|
return spec.secondaryValAxis != null && s.valAxis == spec.secondaryValAxis;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Integer> intersect(List<Integer> family, List<Integer> prim) {
|
||||||
|
List<Integer> out = new ArrayList<>();
|
||||||
|
for (int si : family) {
|
||||||
|
if (prim.contains(si)) {
|
||||||
|
out.add(si);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Диапазон stacked-семейства по кумулятивным строкам первичных серий
|
||||||
|
* (строка j ↔ family.get(j)); как stackedRange — границы от 0. */
|
||||||
|
private static double[] cumRange(double[][] cum, List<Integer> family, List<Integer> prim) {
|
||||||
|
double min = 0;
|
||||||
|
double max = 0;
|
||||||
|
for (int j = 0; j < family.size() && j < cum.length; j++) {
|
||||||
|
if (!prim.contains(family.get(j))) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (double v : cum[j]) {
|
||||||
|
min = Math.min(min, v);
|
||||||
|
max = Math.max(max, v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new double[]{min, max};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Объединение диапазонов семейств первичной оси; все null → {0,1}
|
||||||
|
* (как valueRange на пустом наборе). */
|
||||||
|
private static double[] mergeRanges(double[]... parts) {
|
||||||
|
double min = Double.MAX_VALUE;
|
||||||
|
double max = -Double.MAX_VALUE;
|
||||||
|
for (double[] r : parts) {
|
||||||
|
if (r == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
min = Math.min(min, r[0]);
|
||||||
|
max = Math.max(max, r[1]);
|
||||||
|
}
|
||||||
|
if (min > max) {
|
||||||
|
return new double[]{0, 1};
|
||||||
|
}
|
||||||
|
return new double[]{min, max};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Word укрупняет шаг оси значений, если подписи не влезают: интервал между
|
||||||
|
* делениями не меньше ~2,5 высоты строки подписи. В word-export.pdf у line chart
|
||||||
|
* (область ~71 pt, подписи 9 pt) шаг вышел 2 (0…6), а не 1 (0…5).
|
||||||
|
* Явные c:majorUnit/c:max не трогаем. Возвращает {hi, unit}. */
|
||||||
|
private static double[] fitUnit(ChartSpec.AxisSpec axis, double lo, double hi, double unit,
|
||||||
|
double dataMin, double dataMax, double axisLen) {
|
||||||
|
if (axis.labelStyle == null || axis.deleted || axis.majorUnit != null
|
||||||
|
|| axis.max != null) {
|
||||||
|
return new double[]{hi, unit};
|
||||||
|
}
|
||||||
|
double labelH = DrawMlText.textHeight(axis.labelStyle);
|
||||||
|
while (hi - lo > unit && axisLen / ((hi - lo) / unit) < 2.5 * labelH) {
|
||||||
|
unit = ChartRenderer.nextUnit(unit);
|
||||||
|
double top = dataMax + (dataMax - dataMin) / 20.0;
|
||||||
|
hi = Math.max(lo + unit, Math.ceil(top / unit - 1e-9) * unit);
|
||||||
|
}
|
||||||
|
return new double[]{hi, unit};
|
||||||
}
|
}
|
||||||
|
|
||||||
static List<String> categoriesOf(ChartSpec spec, int nCat) {
|
static List<String> categoriesOf(ChartSpec spec, int nCat) {
|
||||||
@@ -241,6 +426,26 @@ final class CartesianPainter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Подписи вторичной оси значений: справа от правого края области построения,
|
||||||
|
* выравнивание влево, вертикальная центровка по делению (§21.2.2.226). */
|
||||||
|
private static void drawSecondaryValueLabels(Graphics2D g, List<String> labels,
|
||||||
|
Rectangle2D plot, DrawMlText.Style style,
|
||||||
|
double lo, double hi) {
|
||||||
|
if (style == null || labels.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
double h = DrawMlText.textHeight(style) + 2;
|
||||||
|
double span = hi - lo;
|
||||||
|
for (int i = 0; i < labels.size(); i++) {
|
||||||
|
double t = span == 0 ? 0 : i / (double) (labels.size() - 1);
|
||||||
|
double w = DrawMlText.textWidth(labels.get(i), style);
|
||||||
|
double y = plot.getY() + plot.getHeight() * (1 - t);
|
||||||
|
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(labels.get(i), style, "l")),
|
||||||
|
new Rectangle2D.Double(plot.getMaxX() + 3, y - h / 2, w, h),
|
||||||
|
"l", "ctr", 1.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static double valuePos(double v, double lo, double hi, Rectangle2D plot,
|
private static double valuePos(double v, double lo, double hi, Rectangle2D plot,
|
||||||
boolean horizontal) {
|
boolean horizontal) {
|
||||||
double t = (v - lo) / (hi - lo);
|
double t = (v - lo) / (hi - lo);
|
||||||
@@ -261,10 +466,15 @@ final class CartesianPainter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static void drawLines(Graphics2D g, ChartSpec spec, Rectangle2D plot,
|
private static void drawLines(Graphics2D g, ChartSpec spec, Rectangle2D plot,
|
||||||
List<Color> palette, double lo, double hi, int nCat,
|
List<Color> palette, double lo, double hi,
|
||||||
|
double secLo, double secHi, List<Integer> idx, int nCat,
|
||||||
boolean horizontal, boolean reversed, double[][] cum) {
|
boolean horizontal, boolean reversed, double[][] cum) {
|
||||||
for (int si = 0; si < spec.series.size(); si++) {
|
for (int j = 0; j < idx.size(); j++) {
|
||||||
|
int si = idx.get(j);
|
||||||
ChartSpec.Series s = spec.series.get(si);
|
ChartSpec.Series s = spec.series.get(si);
|
||||||
|
boolean sec = onSecondary(s, spec);
|
||||||
|
double sLo = sec ? secLo : lo;
|
||||||
|
double sHi = sec ? secHi : hi;
|
||||||
Color c = s.lineColor != null ? s.lineColor : s.fillAt(si, palette);
|
Color c = s.lineColor != null ? s.lineColor : s.fillAt(si, palette);
|
||||||
double width = s.lineWidth > 0 ? s.lineWidth : 2.25;
|
double width = s.lineWidth > 0 ? s.lineWidth : 2.25;
|
||||||
g.setColor(c);
|
g.setColor(c);
|
||||||
@@ -272,10 +482,10 @@ final class CartesianPainter {
|
|||||||
BasicStroke.JOIN_ROUND));
|
BasicStroke.JOIN_ROUND));
|
||||||
List<Double> along = new ArrayList<>();
|
List<Double> along = new ArrayList<>();
|
||||||
List<Double> cross = new ArrayList<>();
|
List<Double> cross = new ArrayList<>();
|
||||||
if (cum != null) {
|
if (cum != null && !sec) {
|
||||||
for (int i = 0; i < nCat; i++) {
|
for (int i = 0; i < nCat; i++) {
|
||||||
along.add(catPos(i, nCat, plot, horizontal, reversed));
|
along.add(catPos(i, nCat, plot, horizontal, reversed));
|
||||||
cross.add(valuePos(cum[si][i], lo, hi, plot, horizontal));
|
cross.add(valuePos(cum[j][i], sLo, sHi, plot, horizontal));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for (int i = 0; i < s.values.size(); i++) {
|
for (int i = 0; i < s.values.size(); i++) {
|
||||||
@@ -284,7 +494,7 @@ final class CartesianPainter {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
along.add(catPos(i, nCat, plot, horizontal, reversed));
|
along.add(catPos(i, nCat, plot, horizontal, reversed));
|
||||||
cross.add(valuePos(v, lo, hi, plot, horizontal));
|
cross.add(valuePos(v, sLo, sHi, plot, horizontal));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (along.size() >= MIN_POLYLINE_POINTS) {
|
if (along.size() >= MIN_POLYLINE_POINTS) {
|
||||||
@@ -313,10 +523,14 @@ final class CartesianPainter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static void drawAreas(Graphics2D g, ChartSpec spec, Rectangle2D plot,
|
private static void drawAreas(Graphics2D g, ChartSpec spec, Rectangle2D plot,
|
||||||
List<Color> palette, double lo, double hi, int nCat,
|
List<Color> palette, double lo, double hi,
|
||||||
|
double secLo, double secHi, List<Integer> idx, int nCat,
|
||||||
boolean horizontal, boolean reversed) {
|
boolean horizontal, boolean reversed) {
|
||||||
for (int si = 0; si < spec.series.size(); si++) {
|
for (int si : idx) {
|
||||||
ChartSpec.Series s = spec.series.get(si);
|
ChartSpec.Series s = spec.series.get(si);
|
||||||
|
boolean sec = onSecondary(s, spec);
|
||||||
|
double sLo = sec ? secLo : lo;
|
||||||
|
double sHi = sec ? secHi : hi;
|
||||||
Color c = s.fill != null ? s.fill : s.fillAt(si, palette);
|
Color c = s.fill != null ? s.fill : s.fillAt(si, palette);
|
||||||
List<Double> along = new ArrayList<>();
|
List<Double> along = new ArrayList<>();
|
||||||
List<Double> cross = new ArrayList<>();
|
List<Double> cross = new ArrayList<>();
|
||||||
@@ -326,7 +540,7 @@ final class CartesianPainter {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
along.add(catPos(i, nCat, plot, horizontal, reversed));
|
along.add(catPos(i, nCat, plot, horizontal, reversed));
|
||||||
cross.add(valuePos(v, lo, hi, plot, horizontal));
|
cross.add(valuePos(v, sLo, sHi, plot, horizontal));
|
||||||
}
|
}
|
||||||
if (along.size() < MIN_POLYLINE_POINTS) {
|
if (along.size() < MIN_POLYLINE_POINTS) {
|
||||||
continue;
|
continue;
|
||||||
@@ -342,7 +556,7 @@ final class CartesianPainter {
|
|||||||
// §21.2.2.5 c:areaChart), а не хордой последняя→первая: замыкаем
|
// §21.2.2.5 c:areaChart), а не хордой последняя→первая: замыкаем
|
||||||
// путь по базовой линии (значение lo).
|
// путь по базовой линии (значение lo).
|
||||||
// Регрессия — CartesianPainterTest#areaFill_closesToBaseline.
|
// Регрессия — CartesianPainterTest#areaFill_closesToBaseline.
|
||||||
double base = valuePos(lo, lo, hi, plot, horizontal);
|
double base = valuePos(sLo, sLo, sHi, plot, horizontal);
|
||||||
p.lineTo(toX(along.get(along.size() - 1), base, horizontal),
|
p.lineTo(toX(along.get(along.size() - 1), base, horizontal),
|
||||||
toY(along.get(along.size() - 1), base, horizontal));
|
toY(along.get(along.size() - 1), base, horizontal));
|
||||||
p.lineTo(toX(along.get(0), base, horizontal), toY(along.get(0), base, horizontal));
|
p.lineTo(toX(along.get(0), base, horizontal), toY(along.get(0), base, horizontal));
|
||||||
@@ -365,21 +579,26 @@ final class CartesianPainter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static void drawBars(Graphics2D g, ChartSpec spec, Rectangle2D plot,
|
private static void drawBars(Graphics2D g, ChartSpec spec, Rectangle2D plot,
|
||||||
List<Color> palette, double lo, double hi, int nCat,
|
List<Color> palette, double lo, double hi,
|
||||||
|
double secLo, double secHi, List<Integer> idx, int nCat,
|
||||||
boolean horizontal, boolean reversed, double[][] cum) {
|
boolean horizontal, boolean reversed, double[][] cum) {
|
||||||
int nSer = spec.series.size();
|
int nSer = idx.size();
|
||||||
double slot = (horizontal ? plot.getHeight() : plot.getWidth()) / nCat;
|
double slot = (horizontal ? plot.getHeight() : plot.getWidth()) / nCat;
|
||||||
if (cum != null) {
|
if (cum != null) {
|
||||||
// §21.2.2.76: stacked — один столбец на категорию, сегмент ряда si — от
|
// §21.2.2.76: stacked — один столбец на категорию, сегмент ряда — от
|
||||||
// кумулятивной суммы предыдущих рядов (0 для si=0) до cum[si][i]; null —
|
// кумулятивной суммы предыдущих рядов семейства (0 для j=0) до cum[j][i];
|
||||||
// сегмента нет. Ширина — как у одиночного ряда (c:gapWidth), c:overlap
|
// null — сегмента нет. Ширина — как у одиночного ряда (c:gapWidth), c:overlap
|
||||||
// к stacked не применяется. Семантика суммы — как у stacked-ветки
|
// к stacked не применяется. Семантика суммы — как у stacked-ветки
|
||||||
// Cartesian3dPainter (простая накапливающая сумма, смешанные знаки —
|
// Cartesian3dPainter (простая накапливающая сумма, смешанные знаки —
|
||||||
// по stackedRange). Регрессия — CartesianPainterTest#stackedBar_seriesStackCumulatively,
|
// по stackedRange). Регрессия — CartesianPainterTest#stackedBar_seriesStackCumulatively,
|
||||||
// фикстура samples/chart-types.docx.
|
// фикстура samples/chart-types.docx.
|
||||||
double barW = slot / (1 + spec.gapWidth / 100.0);
|
double barW = slot / (1 + spec.gapWidth / 100.0);
|
||||||
for (int si = 0; si < nSer; si++) {
|
for (int j = 0; j < nSer; j++) {
|
||||||
|
int si = idx.get(j);
|
||||||
ChartSpec.Series s = spec.series.get(si);
|
ChartSpec.Series s = spec.series.get(si);
|
||||||
|
boolean sec = onSecondary(s, spec);
|
||||||
|
double sLo = sec ? secLo : lo;
|
||||||
|
double sHi = sec ? secHi : hi;
|
||||||
for (int i = 0; i < s.values.size(); i++) {
|
for (int i = 0; i < s.values.size(); i++) {
|
||||||
Double v = s.values.get(i);
|
Double v = s.values.get(i);
|
||||||
if (v == null) {
|
if (v == null) {
|
||||||
@@ -389,9 +608,11 @@ final class CartesianPainter {
|
|||||||
g.setColor(c);
|
g.setColor(c);
|
||||||
double center = catPos(i, nCat, plot, horizontal, reversed);
|
double center = catPos(i, nCat, plot, horizontal, reversed);
|
||||||
double start = center - barW / 2;
|
double start = center - barW / 2;
|
||||||
double prev = si == 0 ? 0 : cum[si - 1][i];
|
// stacked-серия на вторичной оси (враждебный XML) — по сырым значениям.
|
||||||
double p0 = valuePos(prev, lo, hi, plot, horizontal);
|
double prev = j == 0 || sec ? 0 : cum[j - 1][i];
|
||||||
double p1 = valuePos(cum[si][i], lo, hi, plot, horizontal);
|
double top = sec ? v : cum[j][i];
|
||||||
|
double p0 = valuePos(prev, sLo, sHi, plot, horizontal);
|
||||||
|
double p1 = valuePos(top, sLo, sHi, plot, horizontal);
|
||||||
if (horizontal) {
|
if (horizontal) {
|
||||||
g.fill(new Rectangle2D.Double(Math.min(p0, p1), start,
|
g.fill(new Rectangle2D.Double(Math.min(p0, p1), start,
|
||||||
Math.abs(p1 - p0), barW));
|
Math.abs(p1 - p0), barW));
|
||||||
@@ -408,7 +629,8 @@ final class CartesianPainter {
|
|||||||
// (Word default gapWidth=150, один ряд => bar = 0.4 слота).
|
// (Word default gapWidth=150, один ряд => bar = 0.4 слота).
|
||||||
// Шаг между рядами внутри группы step = barW·(1 - overlap/100):
|
// Шаг между рядами внутри группы step = barW·(1 - overlap/100):
|
||||||
// overlap>0 — перекрытие, <0 — раздвижка; раздвижка не выносит
|
// overlap>0 — перекрытие, <0 — раздвижка; раздвижка не выносит
|
||||||
// группу за пределы слота.
|
// группу за пределы слота. Ширина слота — по числу бар-серий (nSer),
|
||||||
|
// ряды других семейств (линия combo) в слот не лезут.
|
||||||
double overlap = Math.max(-100, Math.min(100, spec.overlap));
|
double overlap = Math.max(-100, Math.min(100, spec.overlap));
|
||||||
double barW = slot / (Math.max(1, nSer) + spec.gapWidth / 100.0);
|
double barW = slot / (Math.max(1, nSer) + spec.gapWidth / 100.0);
|
||||||
double step = barW * (1 - overlap / 100.0);
|
double step = barW * (1 - overlap / 100.0);
|
||||||
@@ -416,9 +638,13 @@ final class CartesianPainter {
|
|||||||
step = Math.min(step, (slot - barW) / (nSer - 1));
|
step = Math.min(step, (slot - barW) / (nSer - 1));
|
||||||
}
|
}
|
||||||
double groupW = barW + (nSer - 1) * step;
|
double groupW = barW + (nSer - 1) * step;
|
||||||
double zero = valuePos(0, lo, hi, plot, horizontal);
|
for (int j = 0; j < nSer; j++) {
|
||||||
for (int si = 0; si < nSer; si++) {
|
int si = idx.get(j);
|
||||||
ChartSpec.Series s = spec.series.get(si);
|
ChartSpec.Series s = spec.series.get(si);
|
||||||
|
boolean sec = onSecondary(s, spec);
|
||||||
|
double sLo = sec ? secLo : lo;
|
||||||
|
double sHi = sec ? secHi : hi;
|
||||||
|
double zero = valuePos(0, sLo, sHi, plot, horizontal);
|
||||||
for (int i = 0; i < s.values.size(); i++) {
|
for (int i = 0; i < s.values.size(); i++) {
|
||||||
Double v = s.values.get(i);
|
Double v = s.values.get(i);
|
||||||
if (v == null) {
|
if (v == null) {
|
||||||
@@ -427,8 +653,8 @@ final class CartesianPainter {
|
|||||||
Color c = s.fillAt(i, palette);
|
Color c = s.fillAt(i, palette);
|
||||||
g.setColor(c);
|
g.setColor(c);
|
||||||
double center = catPos(i, nCat, plot, horizontal, reversed);
|
double center = catPos(i, nCat, plot, horizontal, reversed);
|
||||||
double start = center - groupW / 2 + si * step;
|
double start = center - groupW / 2 + j * step;
|
||||||
double end = valuePos(v, lo, hi, plot, horizontal);
|
double end = valuePos(v, sLo, sHi, plot, horizontal);
|
||||||
if (horizontal) {
|
if (horizontal) {
|
||||||
g.fill(new Rectangle2D.Double(Math.min(zero, end), start,
|
g.fill(new Rectangle2D.Double(Math.min(zero, end), start,
|
||||||
Math.abs(end - zero), barW));
|
Math.abs(end - zero), barW));
|
||||||
|
|||||||
@@ -251,8 +251,11 @@ final class ChartRenderer {
|
|||||||
for (ChartSpec.Series s : spec.series) {
|
for (ChartSpec.Series s : spec.series) {
|
||||||
Color c = s.lineColor != null ? s.lineColor
|
Color c = s.lineColor != null ? s.lineColor
|
||||||
: s.fillAt(0, palette);
|
: s.fillAt(0, palette);
|
||||||
boolean lineLike = spec.type == ChartSpec.Type.LINE
|
// Combo: у ряда свой способ отрисовки — линия в легенде только у LINE-рядов.
|
||||||
|| spec.type == ChartSpec.Type.SCATTER;
|
boolean lineLike = s.renderAs != null
|
||||||
|
? s.renderAs == ChartSpec.Type.LINE
|
||||||
|
: spec.type == ChartSpec.Type.LINE
|
||||||
|
|| spec.type == ChartSpec.Type.SCATTER;
|
||||||
legend.entries.add(new Legend.Entry(s.name == null ? "" : s.name, c,
|
legend.entries.add(new Legend.Entry(s.name == null ? "" : s.name, c,
|
||||||
lineLike ? Math.max(1.0, s.lineWidth > 0 ? s.lineWidth : 2.25) : -1));
|
lineLike ? Math.max(1.0, s.lineWidth > 0 ? s.lineWidth : 2.25) : -1));
|
||||||
}
|
}
|
||||||
@@ -286,10 +289,15 @@ final class ChartRenderer {
|
|||||||
|
|
||||||
/** Диапазон всех значений всех рядов. */
|
/** Диапазон всех значений всех рядов. */
|
||||||
static double[] valueRange(ChartSpec spec) {
|
static double[] valueRange(ChartSpec spec) {
|
||||||
|
return valueRange(spec, allIndices(spec));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Диапазон значений подмножества рядов idx (combo: по своей оси значений). */
|
||||||
|
static double[] valueRange(ChartSpec spec, List<Integer> idx) {
|
||||||
double min = Double.MAX_VALUE;
|
double min = Double.MAX_VALUE;
|
||||||
double max = -Double.MAX_VALUE;
|
double max = -Double.MAX_VALUE;
|
||||||
for (ChartSpec.Series s : spec.series) {
|
for (int si : idx) {
|
||||||
for (Double v : s.values) {
|
for (Double v : spec.series.get(si).values) {
|
||||||
if (v != null) {
|
if (v != null) {
|
||||||
min = Math.min(min, v);
|
min = Math.min(min, v);
|
||||||
max = Math.max(max, v);
|
max = Math.max(max, v);
|
||||||
@@ -311,6 +319,15 @@ final class ChartRenderer {
|
|||||||
return new double[]{min, max};
|
return new double[]{min, max};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Индексы всех рядов — делегат для полных перегрузок. */
|
||||||
|
private static List<Integer> allIndices(ChartSpec spec) {
|
||||||
|
List<Integer> idx = new ArrayList<>();
|
||||||
|
for (int i = 0; i < spec.series.size(); i++) {
|
||||||
|
idx.add(i);
|
||||||
|
}
|
||||||
|
return idx;
|
||||||
|
}
|
||||||
|
|
||||||
/** c:grouping stacked/percentStacked (§21.2.2.76). */
|
/** c:grouping stacked/percentStacked (§21.2.2.76). */
|
||||||
static boolean isStacked(String grouping) {
|
static boolean isStacked(String grouping) {
|
||||||
return "stacked".equalsIgnoreCase(grouping)
|
return "stacked".equalsIgnoreCase(grouping)
|
||||||
@@ -320,16 +337,23 @@ final class ChartRenderer {
|
|||||||
/** Кумулятивные значения stacked: cum[si][c] — сумма рядов 0..si в категории c;
|
/** Кумулятивные значения stacked: cum[si][c] — сумма рядов 0..si в категории c;
|
||||||
* percentStacked — доля от суммы категории ×100 (сумма 0 → 0). */
|
* percentStacked — доля от суммы категории ×100 (сумма 0 → 0). */
|
||||||
static double[][] stackedCumulative(ChartSpec spec, boolean percent) {
|
static double[][] stackedCumulative(ChartSpec spec, boolean percent) {
|
||||||
int nSer = spec.series.size();
|
return stackedCumulative(spec, allIndices(spec), percent);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Кумулятивные значения stacked по подмножеству рядов idx (combo: накопление
|
||||||
|
* только внутри своего семейства); cum[j][c], j — позиция в idx. */
|
||||||
|
static double[][] stackedCumulative(ChartSpec spec, List<Integer> idx, boolean percent) {
|
||||||
|
int nSer = idx.size();
|
||||||
int nCat = 0;
|
int nCat = 0;
|
||||||
for (ChartSpec.Series s : spec.series) {
|
for (int si : idx) {
|
||||||
nCat = Math.max(nCat, s.values.size());
|
nCat = Math.max(nCat, spec.series.get(si).values.size());
|
||||||
}
|
}
|
||||||
double[] totals = new double[nCat];
|
double[] totals = new double[nCat];
|
||||||
if (percent) {
|
if (percent) {
|
||||||
for (ChartSpec.Series s : spec.series) {
|
for (int si : idx) {
|
||||||
for (int c = 0; c < s.values.size(); c++) {
|
List<Double> vals = spec.series.get(si).values;
|
||||||
Double v = s.values.get(c);
|
for (int c = 0; c < vals.size(); c++) {
|
||||||
|
Double v = vals.get(c);
|
||||||
if (v != null) {
|
if (v != null) {
|
||||||
totals[c] += v;
|
totals[c] += v;
|
||||||
}
|
}
|
||||||
@@ -339,15 +363,15 @@ final class ChartRenderer {
|
|||||||
double[][] cum = new double[nSer][nCat];
|
double[][] cum = new double[nSer][nCat];
|
||||||
for (int c = 0; c < nCat; c++) {
|
for (int c = 0; c < nCat; c++) {
|
||||||
double running = 0;
|
double running = 0;
|
||||||
for (int si = 0; si < nSer; si++) {
|
for (int j = 0; j < nSer; j++) {
|
||||||
List<Double> vals = spec.series.get(si).values;
|
List<Double> vals = spec.series.get(idx.get(j)).values;
|
||||||
Double v = c < vals.size() ? vals.get(c) : null;
|
Double v = c < vals.size() ? vals.get(c) : null;
|
||||||
double add = v == null ? 0 : v;
|
double add = v == null ? 0 : v;
|
||||||
if (percent) {
|
if (percent) {
|
||||||
add = totals[c] == 0 ? 0 : add / totals[c] * 100.0;
|
add = totals[c] == 0 ? 0 : add / totals[c] * 100.0;
|
||||||
}
|
}
|
||||||
running += add;
|
running += add;
|
||||||
cum[si][c] = running;
|
cum[j][c] = running;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return cum;
|
return cum;
|
||||||
|
|||||||
@@ -58,8 +58,10 @@ import java.awt.Color;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Модель графика DrawingML (c:chartSpace), сокращённая до того, что
|
* Модель графика DrawingML (c:chartSpace), сокращённая до того, что
|
||||||
@@ -113,6 +115,15 @@ final class ChartSpec {
|
|||||||
final List<Double> bubbleSizes = new ArrayList<>();
|
final List<Double> bubbleSizes = new ArrayList<>();
|
||||||
/** c:shape ряда bar3D (MS-OI29500 §2.1.1545(b)); null = дефолт диаграммы ({@link #shape3d}). */
|
/** c:shape ряда bar3D (MS-OI29500 §2.1.1545(b)); null = дефолт диаграммы ({@link #shape3d}). */
|
||||||
String shape3d;
|
String shape3d;
|
||||||
|
/** Способ отрисовки ряда в combo-диаграмме (несколько групп в одном c:plotArea,
|
||||||
|
* ECMA-376 §21.2.2.145): BAR/BAR_HORIZONTAL/LINE/AREA по группе-источнику.
|
||||||
|
* null = рисоваться по {@link ChartSpec#type} (не-combo и ручные спеки). */
|
||||||
|
Type renderAs;
|
||||||
|
/** c:grouping (§21.2.2.76) СВОЕЙ группы ряда (combo: у групп разные накопления);
|
||||||
|
* null → фолбэк на {@link ChartSpec#grouping}. */
|
||||||
|
String grouping;
|
||||||
|
/** Ось значений своей группы (§21.2.2.9 c:axId); null = первичная {@link ChartSpec#valAxis}. */
|
||||||
|
AxisSpec valAxis;
|
||||||
|
|
||||||
Color fillAt(int i, List<Color> palette) {
|
Color fillAt(int i, List<Color> palette) {
|
||||||
Color c = pointFills.get(i);
|
Color c = pointFills.get(i);
|
||||||
@@ -139,6 +150,8 @@ final class ChartSpec {
|
|||||||
/** c:scaling/c:orientation=maxMin (ECMA-376 §21.2.2.130, ST_Orientation §21.2.3.30;
|
/** c:scaling/c:orientation=maxMin (ECMA-376 §21.2.2.130, ST_Orientation §21.2.3.30;
|
||||||
* MS-OI29500 §2.1.1511): значения оси в обратном порядке. */
|
* MS-OI29500 §2.1.1511): значения оси в обратном порядке. */
|
||||||
boolean reversed;
|
boolean reversed;
|
||||||
|
/** c:axId (§21.2.2.9) оси; -1 = элемент отсутствует (привязка групп по id невозможна). */
|
||||||
|
int axId = -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
Type type = Type.UNSUPPORTED;
|
Type type = Type.UNSUPPORTED;
|
||||||
@@ -152,6 +165,9 @@ final class ChartSpec {
|
|||||||
final List<String> categories = new ArrayList<>();
|
final List<String> categories = new ArrayList<>();
|
||||||
AxisSpec valAxis;
|
AxisSpec valAxis;
|
||||||
AxisSpec catAxis;
|
AxisSpec catAxis;
|
||||||
|
/** Вторичная ось значений (combo: группа на своей c:valAx, обычно c:axPos="r", §21.2.2.226);
|
||||||
|
* null = вторичной оси нет. */
|
||||||
|
AxisSpec secondaryValAxis;
|
||||||
AxisSpec serAxis;
|
AxisSpec serAxis;
|
||||||
double rotX = 30;
|
double rotX = 30;
|
||||||
double rotY = 0;
|
double rotY = 0;
|
||||||
@@ -258,17 +274,46 @@ final class ChartSpec {
|
|||||||
|
|
||||||
CTPlotArea pa = chart.getPlotArea();
|
CTPlotArea pa = chart.getPlotArea();
|
||||||
if (pa != null) {
|
if (pa != null) {
|
||||||
|
// Combo (§21.2.2.145): несколько групп в одном plotArea, каждая со своими
|
||||||
|
// c:axId (§21.2.2.9). Записываем диапазоны серий групп и их id осей, привязка — после чтения осей.
|
||||||
|
List<int[]> groupRanges = new ArrayList<>();
|
||||||
|
List<List<Long>> groupAxIds = new ArrayList<>();
|
||||||
|
Type firstType = null;
|
||||||
for (Object group : pa.getAreaChartOrArea3DChartOrLineChart()) {
|
for (Object group : pa.getAreaChartOrArea3DChartOrLineChart()) {
|
||||||
|
List<Long> ids = cartesianAxIds(group);
|
||||||
|
int from = spec.series.size();
|
||||||
readGroup(group, spec, colors, palette);
|
readGroup(group, spec, colors, palette);
|
||||||
|
int to = spec.series.size();
|
||||||
|
if (to > from) {
|
||||||
|
if (firstType == null) {
|
||||||
|
firstType = spec.type;
|
||||||
|
}
|
||||||
|
if (!ids.isEmpty()) {
|
||||||
|
groupRanges.add(new int[]{from, to});
|
||||||
|
groupAxIds.add(ids);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
List<AxisSpec> valAxes = new ArrayList<>();
|
List<AxisSpec> valAxes = new ArrayList<>();
|
||||||
|
Map<Long, AxisSpec> axesById = new HashMap<>();
|
||||||
|
Set<Long> valAxisIds = new HashSet<>();
|
||||||
for (Object ax : pa.getValAxOrCatAxOrDateAx()) {
|
for (Object ax : pa.getValAxOrCatAxOrDateAx()) {
|
||||||
AxisSpec a = readAxis(ax, colors);
|
AxisSpec a = readAxis(ax, colors);
|
||||||
|
if (a.axId >= 0) {
|
||||||
|
axesById.put((long) a.axId, a);
|
||||||
|
}
|
||||||
if (ax instanceof CTValAx) {
|
if (ax instanceof CTValAx) {
|
||||||
spec.valAxis = a;
|
if (a.axId >= 0) {
|
||||||
|
valAxisIds.add((long) a.axId);
|
||||||
|
}
|
||||||
|
if (spec.valAxis == null) {
|
||||||
|
spec.valAxis = a;
|
||||||
|
}
|
||||||
valAxes.add(a);
|
valAxes.add(a);
|
||||||
} else if (ax instanceof CTCatAx) {
|
} else if (ax instanceof CTCatAx) {
|
||||||
spec.catAxis = a;
|
if (spec.catAxis == null) {
|
||||||
|
spec.catAxis = a;
|
||||||
|
}
|
||||||
} else if (ax instanceof CTSerAx) {
|
} else if (ax instanceof CTSerAx) {
|
||||||
spec.serAxis = a;
|
spec.serAxis = a;
|
||||||
} else if (ax instanceof CTDateAx && spec.catAxis == null) {
|
} else if (ax instanceof CTDateAx && spec.catAxis == null) {
|
||||||
@@ -282,6 +327,26 @@ final class ChartSpec {
|
|||||||
&& valAxes.size() >= 2) {
|
&& valAxes.size() >= 2) {
|
||||||
spec.xAxis = valAxes.get(0);
|
spec.xAxis = valAxes.get(0);
|
||||||
spec.valAxis = valAxes.get(1);
|
spec.valAxis = valAxes.get(1);
|
||||||
|
} else {
|
||||||
|
bindGroupAxes(spec, groupRanges, groupAxIds, axesById, valAxisIds);
|
||||||
|
}
|
||||||
|
// Combo: ≥2 различных renderAs среди серий → тип задаёт первая группа
|
||||||
|
// (она определяет ориентацию и первичное семейство отрисовки).
|
||||||
|
Type render0 = null;
|
||||||
|
boolean combo = false;
|
||||||
|
for (Series s : spec.series) {
|
||||||
|
if (s.renderAs == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (render0 == null) {
|
||||||
|
render0 = s.renderAs;
|
||||||
|
} else if (render0 != s.renderAs) {
|
||||||
|
combo = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (combo && firstType != null) {
|
||||||
|
spec.type = firstType;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
readLegend(chart, spec, colors);
|
readLegend(chart, spec, colors);
|
||||||
@@ -292,6 +357,54 @@ final class ChartSpec {
|
|||||||
return spec;
|
return spec;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** c:axId (§21.2.2.9) декартовой группы bar/line/area; пустой список — у прочих групп. */
|
||||||
|
private static List<Long> cartesianAxIds(Object group) {
|
||||||
|
List<CTUnsignedInt> raw;
|
||||||
|
if (group instanceof CTBarChart g) {
|
||||||
|
raw = g.getAxId();
|
||||||
|
} else if (group instanceof CTLineChart g) {
|
||||||
|
raw = g.getAxId();
|
||||||
|
} else if (group instanceof org.docx4j.dml.chart.CTAreaChart g) {
|
||||||
|
raw = g.getAxId();
|
||||||
|
} else {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
List<Long> ids = new ArrayList<>();
|
||||||
|
for (CTUnsignedInt u : raw) {
|
||||||
|
ids.add(u.getVal());
|
||||||
|
}
|
||||||
|
return ids;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Привязка групп combo к осям по c:axId (§21.2.2.9): группа не на первичной оси
|
||||||
|
* значений получает {@link ChartSpec#secondaryValAxis}, её серии — ссылку на неё.
|
||||||
|
* Без axId (ручные JAXB-спеки, группы без серий) — ничего не делает.
|
||||||
|
* Регрессия — ChartSpecTest#combo_barAndLine_renderAsAndAxes. */
|
||||||
|
private static void bindGroupAxes(ChartSpec spec, List<int[]> groupRanges,
|
||||||
|
List<List<Long>> groupAxIds,
|
||||||
|
Map<Long, AxisSpec> axesById, Set<Long> valAxisIds) {
|
||||||
|
for (int gi = 0; gi < groupRanges.size(); gi++) {
|
||||||
|
AxisSpec va = null;
|
||||||
|
for (Long id : groupAxIds.get(gi)) {
|
||||||
|
AxisSpec cand = axesById.get(id);
|
||||||
|
if (cand != null && valAxisIds.contains(id)) {
|
||||||
|
va = cand;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (va == null || va == spec.valAxis) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (spec.secondaryValAxis == null) {
|
||||||
|
spec.secondaryValAxis = va;
|
||||||
|
}
|
||||||
|
int[] range = groupRanges.get(gi);
|
||||||
|
for (int i = range[0]; i < range[1]; i++) {
|
||||||
|
spec.series.get(i).valAxis = va;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static void readChartFrame(CTChartSpace space, ChartSpec spec, DrawMlColor colors) {
|
private static void readChartFrame(CTChartSpace space, ChartSpec spec, DrawMlColor colors) {
|
||||||
CTShapeProperties sp = space.getSpPr();
|
CTShapeProperties sp = space.getSpPr();
|
||||||
if (sp == null) {
|
if (sp == null) {
|
||||||
@@ -372,19 +485,27 @@ final class ChartSpec {
|
|||||||
}
|
}
|
||||||
} else if (group instanceof CTLineChart g) {
|
} else if (group instanceof CTLineChart g) {
|
||||||
spec.type = Type.LINE;
|
spec.type = Type.LINE;
|
||||||
|
String grouping = "standard";
|
||||||
if (g.getGrouping() != null && g.getGrouping().getVal() != null) {
|
if (g.getGrouping() != null && g.getGrouping().getVal() != null) {
|
||||||
spec.grouping = g.getGrouping().getVal().value();
|
spec.grouping = g.getGrouping().getVal().value();
|
||||||
|
grouping = spec.grouping;
|
||||||
}
|
}
|
||||||
for (CTLineSer s : g.getSer()) {
|
for (CTLineSer s : g.getSer()) {
|
||||||
spec.series.add(readLineSer(s, colors));
|
Series ser = readLineSer(s, colors);
|
||||||
|
ser.renderAs = Type.LINE;
|
||||||
|
ser.grouping = grouping;
|
||||||
|
spec.series.add(ser);
|
||||||
}
|
}
|
||||||
} else if (group instanceof CTBarChart g) {
|
} else if (group instanceof CTBarChart g) {
|
||||||
boolean horizontal = g.getBarDir() != null
|
boolean horizontal = g.getBarDir() != null
|
||||||
&& g.getBarDir().getVal() != null
|
&& g.getBarDir().getVal() != null
|
||||||
&& "bar".equalsIgnoreCase(g.getBarDir().getVal().value());
|
&& "bar".equalsIgnoreCase(g.getBarDir().getVal().value());
|
||||||
spec.type = horizontal ? Type.BAR_HORIZONTAL : Type.BAR;
|
Type barType = horizontal ? Type.BAR_HORIZONTAL : Type.BAR;
|
||||||
|
spec.type = barType;
|
||||||
|
String grouping = "standard";
|
||||||
if (g.getGrouping() != null && g.getGrouping().getVal() != null) {
|
if (g.getGrouping() != null && g.getGrouping().getVal() != null) {
|
||||||
spec.grouping = g.getGrouping().getVal().value();
|
spec.grouping = g.getGrouping().getVal().value();
|
||||||
|
grouping = spec.grouping;
|
||||||
}
|
}
|
||||||
// getVal() у CTGapAmount/CTOverlap — примитив, проверяется только обёртка
|
// getVal() у CTGapAmount/CTOverlap — примитив, проверяется только обёртка
|
||||||
if (g.getGapWidth() != null) {
|
if (g.getGapWidth() != null) {
|
||||||
@@ -399,6 +520,8 @@ final class ChartSpec {
|
|||||||
if (s.getSpPr() != null && s.getSpPr().getSolidFill() != null) {
|
if (s.getSpPr() != null && s.getSpPr().getSolidFill() != null) {
|
||||||
ser.fill = colors.resolveFill(s.getSpPr().getSolidFill());
|
ser.fill = colors.resolveFill(s.getSpPr().getSolidFill());
|
||||||
}
|
}
|
||||||
|
ser.renderAs = barType;
|
||||||
|
ser.grouping = grouping;
|
||||||
spec.series.add(ser);
|
spec.series.add(ser);
|
||||||
}
|
}
|
||||||
} else if (group instanceof org.docx4j.dml.chart.CTAreaChart g) {
|
} else if (group instanceof org.docx4j.dml.chart.CTAreaChart g) {
|
||||||
@@ -410,6 +533,7 @@ final class ChartSpec {
|
|||||||
ser.fill = colors.resolveFill(s.getSpPr().getSolidFill());
|
ser.fill = colors.resolveFill(s.getSpPr().getSolidFill());
|
||||||
}
|
}
|
||||||
readLineProps(s.getSpPr(), ser, colors);
|
readLineProps(s.getSpPr(), ser, colors);
|
||||||
|
ser.renderAs = Type.AREA;
|
||||||
spec.series.add(ser);
|
spec.series.add(ser);
|
||||||
}
|
}
|
||||||
} else if (group instanceof CTSurface3DChart g) {
|
} else if (group instanceof CTSurface3DChart g) {
|
||||||
@@ -831,6 +955,7 @@ final class ChartSpec {
|
|||||||
CTTextBody txPr;
|
CTTextBody txPr;
|
||||||
CTShapeProperties spPr;
|
CTShapeProperties spPr;
|
||||||
String numFmt;
|
String numFmt;
|
||||||
|
CTUnsignedInt axId;
|
||||||
if (ax instanceof CTCatAx c) {
|
if (ax instanceof CTCatAx c) {
|
||||||
scaling = c.getScaling();
|
scaling = c.getScaling();
|
||||||
deleted = c.getDelete();
|
deleted = c.getDelete();
|
||||||
@@ -838,6 +963,7 @@ final class ChartSpec {
|
|||||||
grid = c.getMajorGridlines();
|
grid = c.getMajorGridlines();
|
||||||
txPr = c.getTxPr();
|
txPr = c.getTxPr();
|
||||||
spPr = c.getSpPr();
|
spPr = c.getSpPr();
|
||||||
|
axId = c.getAxId();
|
||||||
numFmt = c.getNumFmt() != null ? c.getNumFmt().getFormatCode() : "General";
|
numFmt = c.getNumFmt() != null ? c.getNumFmt().getFormatCode() : "General";
|
||||||
} else if (ax instanceof CTValAx c) {
|
} else if (ax instanceof CTValAx c) {
|
||||||
scaling = c.getScaling();
|
scaling = c.getScaling();
|
||||||
@@ -846,6 +972,7 @@ final class ChartSpec {
|
|||||||
grid = c.getMajorGridlines();
|
grid = c.getMajorGridlines();
|
||||||
txPr = c.getTxPr();
|
txPr = c.getTxPr();
|
||||||
spPr = c.getSpPr();
|
spPr = c.getSpPr();
|
||||||
|
axId = c.getAxId();
|
||||||
numFmt = c.getNumFmt() != null ? c.getNumFmt().getFormatCode() : "General";
|
numFmt = c.getNumFmt() != null ? c.getNumFmt().getFormatCode() : "General";
|
||||||
if (c.getMajorUnit() != null) {
|
if (c.getMajorUnit() != null) {
|
||||||
a.majorUnit = finite(c.getMajorUnit().getVal());
|
a.majorUnit = finite(c.getMajorUnit().getVal());
|
||||||
@@ -857,6 +984,7 @@ final class ChartSpec {
|
|||||||
grid = c.getMajorGridlines();
|
grid = c.getMajorGridlines();
|
||||||
txPr = c.getTxPr();
|
txPr = c.getTxPr();
|
||||||
spPr = c.getSpPr();
|
spPr = c.getSpPr();
|
||||||
|
axId = c.getAxId();
|
||||||
numFmt = "General";
|
numFmt = "General";
|
||||||
} else if (ax instanceof CTDateAx c) {
|
} else if (ax instanceof CTDateAx c) {
|
||||||
scaling = c.getScaling();
|
scaling = c.getScaling();
|
||||||
@@ -865,10 +993,14 @@ final class ChartSpec {
|
|||||||
grid = c.getMajorGridlines();
|
grid = c.getMajorGridlines();
|
||||||
txPr = c.getTxPr();
|
txPr = c.getTxPr();
|
||||||
spPr = c.getSpPr();
|
spPr = c.getSpPr();
|
||||||
|
axId = c.getAxId();
|
||||||
numFmt = c.getNumFmt() != null ? c.getNumFmt().getFormatCode() : "General";
|
numFmt = c.getNumFmt() != null ? c.getNumFmt().getFormatCode() : "General";
|
||||||
} else {
|
} else {
|
||||||
return a;
|
return a;
|
||||||
}
|
}
|
||||||
|
if (axId != null && axId.getVal() >= 0 && axId.getVal() <= Integer.MAX_VALUE) {
|
||||||
|
a.axId = (int) axId.getVal();
|
||||||
|
}
|
||||||
a.deleted = isTrue(deleted);
|
a.deleted = isTrue(deleted);
|
||||||
a.pos = pos != null && pos.getVal() != null ? pos.getVal().value() : a.pos;
|
a.pos = pos != null && pos.getVal() != null ? pos.getVal().value() : a.pos;
|
||||||
a.numFmt = numFmt;
|
a.numFmt = numFmt;
|
||||||
|
|||||||
@@ -11,11 +11,12 @@ import java.util.zip.ZipEntry;
|
|||||||
import java.util.zip.ZipOutputStream;
|
import java.util.zip.ZipOutputStream;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Генератор фикстуры {@code samples/chart-types.docx}: 13 диаграмм: 9 типов,
|
* Генератор фикстуры {@code samples/chart-types.docx}: 14 диаграмм: 9 типов,
|
||||||
* которых POI не пишет (scatter, bubble, radar, stock, ofPie, bar3D,
|
* которых POI не пишет (scatter, bubble, radar, stock, ofPie, bar3D,
|
||||||
* area3D, line3D, surface2D), + ofPie pie-вариант + lineChart и линейчатая
|
* area3D, line3D, surface2D), + ofPie pie-вариант + lineChart и линейчатая
|
||||||
* (barDir=bar) с c:grouping=stacked + wireframe-поверхность
|
* (barDir=bar) с c:grouping=stacked + wireframe-поверхность
|
||||||
* (c:wireframe val="1") — chart-XML литералами по ECMA-376 §21.2
|
* (c:wireframe val="1") + combo barChart+lineChart на вторичной оси (§21.2.2.145)
|
||||||
|
* — chart-XML литералами по ECMA-376 §21.2
|
||||||
* (фикстура проходит docs/standards/validate-fixtures.py). Регрессия —
|
* (фикстура проходит docs/standards/validate-fixtures.py). Регрессия —
|
||||||
* WordPdfConverterTest#chartTypes_allTypesRenderAsImages.
|
* WordPdfConverterTest#chartTypes_allTypesRenderAsImages.
|
||||||
*
|
*
|
||||||
@@ -39,7 +40,8 @@ public final class ChartTypesDocxGenerator {
|
|||||||
"Точечная", "Пузырьковая", "Лепестковая", "Биржевая",
|
"Точечная", "Пузырьковая", "Лепестковая", "Биржевая",
|
||||||
"Кольцевая-доля", "Объёмная с столбцами", "Объёмная с областями",
|
"Кольцевая-доля", "Объёмная с столбцами", "Объёмная с областями",
|
||||||
"Объёмная с линиями", "Поверхность", "Поверхность без заливки",
|
"Объёмная с линиями", "Поверхность", "Поверхность без заливки",
|
||||||
"График с накоплением", "Вторичная круговая", "Линейчатая с накоплением");
|
"График с накоплением", "Вторичная круговая", "Линейчатая с накоплением",
|
||||||
|
"Комбинация");
|
||||||
List<String> charts = new ArrayList<>();
|
List<String> charts = new ArrayList<>();
|
||||||
charts.add(scatter());
|
charts.add(scatter());
|
||||||
charts.add(bubble());
|
charts.add(bubble());
|
||||||
@@ -54,6 +56,7 @@ public final class ChartTypesDocxGenerator {
|
|||||||
charts.add(stackedLine());
|
charts.add(stackedLine());
|
||||||
charts.add(ofPiePie());
|
charts.add(ofPiePie());
|
||||||
charts.add(stackedBar());
|
charts.add(stackedBar());
|
||||||
|
charts.add(combo());
|
||||||
|
|
||||||
StringBuilder body = new StringBuilder();
|
StringBuilder body = new StringBuilder();
|
||||||
body.append("<w:p><w:r><w:t>Типы диаграмм</w:t></w:r></w:p>");
|
body.append("<w:p><w:r><w:t>Типы диаграмм</w:t></w:r></w:p>");
|
||||||
@@ -260,6 +263,23 @@ public final class ChartTypesDocxGenerator {
|
|||||||
+ catAx(1, 2) + valAx(2, "b", 1);
|
+ catAx(1, 2) + valAx(2, "b", 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Combo (§21.2.2.145): barChart (первичная ось) + lineChart (вторичная c:valAx pos="r"). */
|
||||||
|
private static String combo() {
|
||||||
|
return "<c:barChart><c:barDir val=\"col\"/><c:grouping val=\"clustered\"/><c:varyColors val=\"0\"/>"
|
||||||
|
+ ser("План", cat("Q1", "Q2", "Q3"), num("5", "9", "7"))
|
||||||
|
+ ser("Факт", cat("Q1", "Q2", "Q3"), num("6", "8", "10"))
|
||||||
|
+ "<c:gapWidth val=\"150\"/>"
|
||||||
|
+ "<c:axId val=\"1\"/><c:axId val=\"2\"/></c:barChart>"
|
||||||
|
+ "<c:lineChart><c:grouping val=\"standard\"/><c:varyColors val=\"0\"/>"
|
||||||
|
+ ser("Тренд", cat("Q1", "Q2", "Q3"), num("120", "80", "150"))
|
||||||
|
+ "<c:axId val=\"3\"/><c:axId val=\"4\"/></c:lineChart>"
|
||||||
|
+ catAx(1, 2) + valAx(2, "l", 1)
|
||||||
|
+ "<c:catAx><c:axId val=\"3\"/><c:scaling>"
|
||||||
|
+ "<c:orientation val=\"minMax\"/></c:scaling><c:delete val=\"1\"/>"
|
||||||
|
+ "<c:axPos val=\"l\"/><c:crossAx val=\"4\"/></c:catAx>"
|
||||||
|
+ valAx(4, "r", 3);
|
||||||
|
}
|
||||||
|
|
||||||
// ---- фрагменты ----
|
// ---- фрагменты ----
|
||||||
|
|
||||||
/** ser с cat (или null) и val. */
|
/** ser с cat (или null) и val. */
|
||||||
|
|||||||
@@ -186,8 +186,8 @@ class WordPdfConverterTest {
|
|||||||
|
|
||||||
String text = norm(pdfText(pdf));
|
String text = norm(pdfText(pdf));
|
||||||
assertTrue(text.contains("Типы диаграмм"), "пропал текст: " + text);
|
assertTrue(text.contains("Типы диаграмм"), "пропал текст: " + text);
|
||||||
assertEquals(13, distinctImageCount(pdf),
|
assertEquals(14, distinctImageCount(pdf),
|
||||||
"каждый из 13 графиков должен стать PNG-вставкой");
|
"каждый из 14 графиков должен стать PNG-вставкой");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+48
@@ -520,6 +520,54 @@ class CartesianPainterTest {
|
|||||||
"stacked: сумма 4→2 — линия снижается, spread=" + (sBlue[2] - sBlue[0]));
|
"stacked: сумма 4→2 — линия снижается, spread=" + (sBlue[2] - sBlue[0]));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Combo (§21.2.2.145): бар-ряд на первичной оси, линейный ряд на вторичной
|
||||||
|
* (secondaryValAxis). Значения 100/200 на первичной шкале ушли бы за холст —
|
||||||
|
* красных пикселей не было бы вовсе, поэтому наличие красной линии в верхней
|
||||||
|
* половине — наблюдаемый признак вторичной шкалы. Два прогона залитых пикселей
|
||||||
|
* в нижней полосе — столбцы нарисованы СТОЛБЦАМИ (в баге вся combo рисовалась
|
||||||
|
* линиями: в нижней полосе был один прогон/пусто).
|
||||||
|
* Регрессия — CartesianPainterTest#combo_barsAndLineOnSecondary_bothDrawn.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void combo_barsAndLineOnSecondary_bothDrawn() {
|
||||||
|
ChartSpec spec = new ChartSpec();
|
||||||
|
spec.type = ChartSpec.Type.BAR;
|
||||||
|
spec.legendPos = null;
|
||||||
|
DrawMlText.Style style = new DrawMlText.Style(9, false, false,
|
||||||
|
new Color(0x59, 0x59, 0x59), "carlito");
|
||||||
|
spec.catAxis = new ChartSpec.AxisSpec();
|
||||||
|
spec.catAxis.labelStyle = style;
|
||||||
|
spec.valAxis = new ChartSpec.AxisSpec();
|
||||||
|
spec.valAxis.labelStyle = style;
|
||||||
|
spec.secondaryValAxis = new ChartSpec.AxisSpec();
|
||||||
|
spec.secondaryValAxis.labelStyle = style;
|
||||||
|
ChartSpec.Series bar = new ChartSpec.Series();
|
||||||
|
bar.renderAs = ChartSpec.Type.BAR;
|
||||||
|
bar.fill = Color.GREEN;
|
||||||
|
bar.values.add(5.0);
|
||||||
|
bar.values.add(10.0);
|
||||||
|
spec.series.add(bar);
|
||||||
|
ChartSpec.Series line = new ChartSpec.Series();
|
||||||
|
line.renderAs = ChartSpec.Type.LINE;
|
||||||
|
line.lineColor = Color.RED;
|
||||||
|
line.marker = false;
|
||||||
|
line.valAxis = spec.secondaryValAxis;
|
||||||
|
line.values.add(100.0);
|
||||||
|
line.values.add(200.0);
|
||||||
|
spec.series.add(line);
|
||||||
|
|
||||||
|
BufferedImage img = ChartRenderer.render(spec, 219.23, 149.08,
|
||||||
|
new DrawMlColor(null));
|
||||||
|
int[] red = yStats(img, Color.RED);
|
||||||
|
assertTrue(red[0] < NO_LINE,
|
||||||
|
"линейный ряд не найден — вторичная шкала не применена (значения ушли за холст)");
|
||||||
|
assertTrue(red[1] < img.getHeight() * 0.6,
|
||||||
|
"медиана красной линии должна быть в верхней части холста: " + red[1]);
|
||||||
|
assertEquals(2, barRuns(spec).size(),
|
||||||
|
"в нижней полосе — два столбца (бар-ряд рисуется столбцами, не линией)");
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* barChart c:grouping=stacked (§21.2.2.76): сегмент ряда на кумулятивной
|
* barChart c:grouping=stacked (§21.2.2.76): сегмент ряда на кумулятивной
|
||||||
* сумме предыдущих. Данные {{2,2,2},{1,1,1}}: в standard верх красного
|
* сумме предыдущих. Данные {{2,2,2},{1,1,1}}: в standard верх красного
|
||||||
|
|||||||
@@ -1264,6 +1264,65 @@ class ChartSpecTest {
|
|||||||
assertEquals(-5.0, spec.valAxis.min, "вторая c:valAx должна остаться осью значений");
|
assertEquals(-5.0, spec.valAxis.min, "вторая c:valAx должна остаться осью значений");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Combo (§21.2.2.145): barChart + lineChart на вторичной оси — renderAs по рядам,
|
||||||
|
* привязка осей по c:axId (§21.2.2.9), тип от первой группы, первичная catAx не затирается. */
|
||||||
|
@Test
|
||||||
|
void combo_barAndLine_renderAsAndAxes() {
|
||||||
|
CTChart chart = new CTChart();
|
||||||
|
CTPlotArea pa = new CTPlotArea();
|
||||||
|
CTBarChart bar = new CTBarChart();
|
||||||
|
bar.getSer().add(new CTBarSer());
|
||||||
|
bar.getAxId().add(uint(1));
|
||||||
|
bar.getAxId().add(uint(2));
|
||||||
|
CTLineChart line = new CTLineChart();
|
||||||
|
line.getSer().add(new CTLineSer());
|
||||||
|
line.getAxId().add(uint(3));
|
||||||
|
line.getAxId().add(uint(4));
|
||||||
|
pa.getAreaChartOrArea3DChartOrLineChart().add(bar);
|
||||||
|
pa.getAreaChartOrArea3DChartOrLineChart().add(line);
|
||||||
|
pa.getValAxOrCatAxOrDateAx().add(catAxWithId(1, false));
|
||||||
|
pa.getValAxOrCatAxOrDateAx().add(valAxWithId(2, 10));
|
||||||
|
pa.getValAxOrCatAxOrDateAx().add(catAxWithId(3, true));
|
||||||
|
pa.getValAxOrCatAxOrDateAx().add(valAxWithId(4, 1000));
|
||||||
|
chart.setPlotArea(pa);
|
||||||
|
ChartSpec spec = ChartSpec.parse(spaceWith(chart), new DrawMlColor(null));
|
||||||
|
|
||||||
|
assertEquals(ChartSpec.Type.BAR, spec.series.get(0).renderAs);
|
||||||
|
assertEquals(ChartSpec.Type.LINE, spec.series.get(1).renderAs);
|
||||||
|
assertEquals(ChartSpec.Type.BAR, spec.type, "тип combo задаёт первая группа");
|
||||||
|
assertEquals(10.0, spec.valAxis.min, "первичная ось значений — первая c:valAx");
|
||||||
|
assertEquals(1000.0, spec.secondaryValAxis.min);
|
||||||
|
assertSame(spec.secondaryValAxis, spec.series.get(1).valAxis);
|
||||||
|
assertNull(spec.series.get(0).valAxis);
|
||||||
|
assertFalse(spec.catAxis.deleted, "первичная catAx — не удалённая вторичная");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Combo с обеими группами на одной оси: вторичной оси нет, renderAs сохранён. */
|
||||||
|
@Test
|
||||||
|
void combo_sameAxis_noSecondary() {
|
||||||
|
CTChart chart = new CTChart();
|
||||||
|
CTPlotArea pa = new CTPlotArea();
|
||||||
|
CTBarChart bar = new CTBarChart();
|
||||||
|
bar.getSer().add(new CTBarSer());
|
||||||
|
bar.getAxId().add(uint(1));
|
||||||
|
bar.getAxId().add(uint(2));
|
||||||
|
CTLineChart line = new CTLineChart();
|
||||||
|
line.getSer().add(new CTLineSer());
|
||||||
|
line.getAxId().add(uint(1));
|
||||||
|
line.getAxId().add(uint(2));
|
||||||
|
pa.getAreaChartOrArea3DChartOrLineChart().add(bar);
|
||||||
|
pa.getAreaChartOrArea3DChartOrLineChart().add(line);
|
||||||
|
pa.getValAxOrCatAxOrDateAx().add(catAxWithId(1, false));
|
||||||
|
pa.getValAxOrCatAxOrDateAx().add(valAxWithId(2, 0));
|
||||||
|
chart.setPlotArea(pa);
|
||||||
|
ChartSpec spec = ChartSpec.parse(spaceWith(chart), new DrawMlColor(null));
|
||||||
|
|
||||||
|
assertNull(spec.secondaryValAxis);
|
||||||
|
assertNull(spec.series.get(1).valAxis);
|
||||||
|
assertEquals(ChartSpec.Type.BAR, spec.series.get(0).renderAs);
|
||||||
|
assertEquals(ChartSpec.Type.LINE, spec.series.get(1).renderAs);
|
||||||
|
}
|
||||||
|
|
||||||
/** c:bubbleChart: bubbleScale/showNegBubbles/sizeRepresents и c:bubbleSize. */
|
/** c:bubbleChart: bubbleScale/showNegBubbles/sizeRepresents и c:bubbleSize. */
|
||||||
@Test
|
@Test
|
||||||
void bubbleSizesAndScaleParsed() {
|
void bubbleSizesAndScaleParsed() {
|
||||||
@@ -1622,6 +1681,21 @@ class ChartSpecTest {
|
|||||||
return ax;
|
return ax;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static CTValAx valAxWithId(int id, double min) {
|
||||||
|
CTValAx ax = valAxWithMin(min);
|
||||||
|
ax.setAxId(uint(id));
|
||||||
|
return ax;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static CTCatAx catAxWithId(int id, boolean deleted) {
|
||||||
|
CTCatAx ax = new CTCatAx();
|
||||||
|
ax.setAxId(uint(id));
|
||||||
|
CTBoolean d = new CTBoolean();
|
||||||
|
d.setVal(deleted);
|
||||||
|
ax.setDelete(d);
|
||||||
|
return ax;
|
||||||
|
}
|
||||||
|
|
||||||
private static CTUpDownBars upDownBars() {
|
private static CTUpDownBars upDownBars() {
|
||||||
CTUpDownBars u = new CTUpDownBars();
|
CTUpDownBars u = new CTUpDownBars();
|
||||||
CTGapAmount gap = new CTGapAmount();
|
CTGapAmount gap = new CTGapAmount();
|
||||||
|
|||||||
Binary file not shown.
Reference in New Issue
Block a user