forked from fiji/SNT
-
Notifications
You must be signed in to change notification settings - Fork 18
/
SNTChart.java
1759 lines (1633 loc) · 64.4 KB
/
SNTChart.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-
* #%L
* Fiji distribution of ImageJ for the life sciences.
* %%
* Copyright (C) 2010 - 2024 Fiji developers.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package sc.fiji.snt.analysis;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;
import java.util.List;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.MenuElement;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import net.imglib2.roi.geom.real.Polygon2D;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.jfree.chart.*;
import org.jfree.chart.annotations.*;
import org.jfree.chart.axis.Axis;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.CategoryAnchor;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.entity.*;
import org.jfree.chart.plot.*;
import org.jfree.chart.plot.flow.FlowPlot;
import org.jfree.chart.renderer.AbstractRenderer;
import org.jfree.chart.renderer.DefaultPolarItemRenderer;
import org.jfree.chart.renderer.LookupPaintScale;
import org.jfree.chart.renderer.category.*;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.title.*;
import org.jfree.chart.ui.*;
import org.jfree.data.Range;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.statistics.HistogramDataset;
import org.jfree.data.statistics.HistogramType;
import org.jfree.data.xy.XYDataset;
import org.scijava.plot.CategoryChart;
import org.scijava.table.Column;
import org.scijava.ui.awt.AWTWindows;
import org.scijava.ui.swing.viewer.plot.jfreechart.*;
import org.scijava.util.ColorRGB;
import org.scijava.util.Colors;
import ij.ImagePlus;
import ij.plugin.ImagesToStack;
import net.imglib2.display.ColorTable;
import sc.fiji.snt.*;
import sc.fiji.snt.gui.GuiUtils;
import sc.fiji.snt.util.SNTColor;
/**
* Extension of {@link ChartPanel} modified for scientific publications and
* convenience methods for plot annotations.
*
* @author Tiago Ferreira
*/
public class SNTChart extends ChartPanel {
static { net.imagej.patcher.LegacyInjector.preinit(); } // required for _every_ class that imports ij. classes
private static final long serialVersionUID = 5245298401153759551L;
private static final Color BACKGROUND_COLOR = Color.WHITE;
private static final List<SNTChart> openInstances = new ArrayList<>();
private List<SNTChart> otherCombinedCharts;
private JFrame frame;
private String title;
static double scalingFactor = 1;
public SNTChart(final String title, final JFreeChart chart) {
this(title, chart, new Dimension((int)(400 * scalingFactor), (int)(400 * scalingFactor)));
}
public SNTChart(final String title, final org.scijava.plot.XYPlot xyplot) {
this(title, new XYPlotConverter().convert(xyplot, JFreeChart.class));
}
public SNTChart(final String title, final CategoryChart categoryChart) {
this(title, new CategoryChartConverter().convert(categoryChart, JFreeChart.class));
}
protected SNTChart(final String title, final JFreeChart chart, final Dimension preferredSize) {
super(chart);
setTitle(title);
if (chart != null) {
chart.setBackgroundPaint(BACKGROUND_COLOR);
chart.setAntiAlias(true);
chart.setTextAntiAlias(true);
if (chart.getLegend() != null) {
chart.getLegend().setBackgroundPaint(chart.getBackgroundPaint());
}
setFontSize(GuiUtils.uiFontSize());
}
// Tweak: Ensure chart is always drawn and not scaled to avoid rendering artifacts
setMinimumDrawWidth(0);
setMaximumDrawWidth(Integer.MAX_VALUE);
setMinimumDrawHeight(0);
setMaximumDrawHeight(Integer.MAX_VALUE);
setBackground(BACKGROUND_COLOR); // provided contrast to otherwise transparent background
if (chart != null) {
customizePopupMenu();
setPreferredSize(preferredSize);
}
try {
setDefaultDirectoryForSaveAs(SNTPrefs.lastknownDir());
} catch (final Exception ignored) {
// Workaround reports of System.getProperty("user.home") not being a valid directory
// (presumably due to modified PATH variables [reported from S Windows 10/11])
SNTUtils.log("SNTChart: Could not set default directory: " + SNTPrefs.lastknownDir());
}
addChartMouseListener(new ChartListener());
}
public JFrame getFrame() {
if (frame == null) {
GuiUtils.setLookAndFeel();
frame = new JFrame(getTitle());
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(true);
if (isCombined()) {
SwingUtilities.invokeLater(() -> {
otherCombinedCharts.forEach(chart -> {
if (chart.frame != null)
chart.frame.setVisible(false);
});
});
}
frame.setContentPane(this);
frame.setBackground(SNTChart.BACKGROUND_COLOR); // provided contrast to otherwise transparent background
frame.setMinimumSize(new Dimension(500,500));
frame.pack();
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(final WindowEvent e) {
openInstances.add(SNTChart.this);
}
@Override
public void windowClosing(final WindowEvent e) {
if (isCombined())
otherCombinedCharts.forEach(SNTChart::dispose);
}
});
}
return frame;
}
private XYPlot getXYPlot() {
return getChart().getXYPlot();
}
private CategoryPlot getCategoryPlot() {
return getChart().getCategoryPlot();
}
/**
* Annotates the specified X-value (XY plots and histograms).
*
* @param xValue the X value to be annotated.
* @param label the annotation label
*/
public void annotateXline(final double xValue, final String label) {
annotateXline(xValue, label, null);
}
/**
* Annotates the specified X-value (XY plots and histograms).
*
* @param xValue the X value to be annotated.
* @param label the annotation label
* @param color the font color
*/
public void annotateXline(final double xValue, final String label, final String color) {
final Marker marker = new ValueMarker(xValue);
final Color c = getColorFromString(color);
marker.setPaint(c);
marker.setLabelBackgroundColor(new Color(255,255,255,0));
if (label != null && !label.isEmpty()) {
marker.setLabelPaint(c);
marker.setLabel(label);
marker.setLabelAnchor(RectangleAnchor.TOP_LEFT);
marker.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
marker.setLabelFont(getXYPlot().getDomainAxis().getTickLabelFont());
}
getXYPlot().addDomainMarker(marker);
}
/**
* Annotates the specified Y-value (XY plots and histograms).
*
* @param yValue the Y value to be annotated.
* @param label the annotation label
*/
public void annotateYline(final double yValue, final String label) {
annotateYline(yValue, label, null);
}
/**
* Annotates the specified Y-value (XY plots and histograms).
*
* @param yValue the Y value to be annotated.
* @param label the annotation label
* @param color the font color
*/
public void annotateYline(final double yValue, final String label, final String color) {
final Color c = getColorFromString(color);
final Marker marker = new ValueMarker(yValue);
marker.setPaint(c);
marker.setLabelBackgroundColor(new Color(255,255,255,0));
if (label != null && !label.isEmpty()) {
marker.setLabelPaint(c);
marker.setLabel(label);
marker.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
marker.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT);
marker.setLabelFont(getXYPlot().getRangeAxis().getTickLabelFont());
}
getXYPlot().addRangeMarker(marker);
}
public void setAxesVisible(final boolean visible) {
if (getChart().getPlot() instanceof XYPlot) {
final XYPlot plot = (XYPlot)(getChart().getPlot());
plot.getDomainAxis().setVisible(visible);
plot.getRangeAxis().setVisible(visible);
} else if (getChart().getPlot() instanceof CategoryPlot) {
final CategoryPlot plot = (CategoryPlot)(getChart().getCategoryPlot());
plot.getDomainAxis().setVisible(visible);
plot.getRangeAxis().setVisible(visible);
}
}
public boolean isLegendVisible() {
try {
return getChart().getLegend().isVisible();
} catch (NullPointerException ignored) {
return false;
}
}
public boolean isOutlineVisible() {
return getChart().getPlot().isOutlineVisible();
}
public boolean isGridlinesVisible() {
if (getChart().getPlot() instanceof XYPlot) {
final XYPlot plot = (XYPlot)(getChart().getPlot());
return plot.isDomainGridlinesVisible() || plot.isRangeGridlinesVisible();
} else if (getChart().getPlot() instanceof CategoryPlot) {
final CategoryPlot plot = (getChart().getCategoryPlot());
return plot.isDomainGridlinesVisible() || plot.isRangeGridlinesVisible();
} else if (getChart().getPlot() instanceof PolarPlot) {
final PolarPlot plot = (PolarPlot)getChart().getPlot();
return plot.isRadiusGridlinesVisible();
}
return false;
}
public void setGridlinesVisible(final boolean visible) {
if (getChart().getPlot() instanceof CombinedRangeXYPlot) {
final List<XYPlot> plots = ((CombinedRangeXYPlot)(getChart().getXYPlot())).getSubplots();
for (final XYPlot plot : plots) {
// CombinedRangeXYPlot do not have domain axis!?
plot.setRangeGridlinesVisible(visible);
plot.setRangeMinorGridlinesVisible(visible);
}
} else if (getChart().getPlot() instanceof XYPlot) {
final XYPlot plot = (XYPlot)(getChart().getPlot());
plot.setDomainGridlinesVisible(visible);
//plot.setDomainMinorGridlinesVisible(visible);
plot.setRangeGridlinesVisible(visible);
//plot.setRangeMinorGridlinesVisible(visible);
} else if (getChart().getPlot() instanceof CategoryPlot) {
final CategoryPlot plot = (getChart().getCategoryPlot());
plot.setDomainGridlinesVisible(visible);
plot.setRangeGridlinesVisible(visible);
//plot.setRangeMinorGridlinesVisible(visible);
} else if (getChart().getPlot() instanceof PolarPlot) {
final PolarPlot plot = (PolarPlot)getChart().getPlot();
plot.setRadiusGridlinesVisible(visible);
plot.setRadiusMinorGridlinesVisible(visible);
plot.setAngleGridlinesVisible(visible);
}
}
public void setOutlineVisible(final boolean visible) {
getChart().getPlot().setOutlineVisible(visible);
}
public void setLegendVisible(final boolean visible) {
if (getChart().getLegend() != null)
getChart().getLegend().setVisible(visible);
}
/**
* Annotates the specified category (Category plots only)
*
* @param category the category to be annotated. Ignored if it does not exist in
* category axis.
* @param label the annotation label
*/
public void annotateCategory(final String category, final String label) {
annotateCategory(category, label, "blue");
}
/**
* Annotates the specified category (Category plots only).
*
* @param category the category to be annotated. Ignored if it does not exist in
* category axis.
* @param label the annotation label
* @param color the annotation color
*/
public void annotateCategory(final String category, final String label, final String color) {
final CategoryPlot catPlot = getCategoryPlot();
final Color c = getColorFromString(color);
final CategoryMarker marker = new CategoryMarker(category, c, new BasicStroke(1.0f,
BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[] { 6.0f, 6.0f }, 0.0f));
marker.setDrawAsLine(true);
catPlot.addDomainMarker(marker, Layer.BACKGROUND);
if (catPlot.getCategories().contains(category) && (label != null && !label.isEmpty())) {
final Range range = catPlot.getRangeAxis().getRange();
final double labelYloc = range.getUpperBound() * 0.50 + range.getLowerBound();
final CategoryTextAnnotation annot = new CategoryTextAnnotation(label, category, labelYloc);
annot.setPaint(c);
annot.setFont(catPlot.getRangeAxis().getTickLabelFont());
annot.setCategoryAnchor(CategoryAnchor.END);
annot.setTextAnchor(TextAnchor.BOTTOM_CENTER);
catPlot.addAnnotation(annot);
}
}
/**
* (Re)colors existing dataset series
*
* @param colors The series colors
*/
public void setColors(final String... colors) {
final Plot plot = getChart().getPlot();
if (plot instanceof CategoryPlot) {
final CategoryItemRenderer renderer = ((CategoryPlot) plot).getRenderer();
final int nSeries = ((CategoryPlot) plot).getDataset().getRowCount();
setDatasetColors(renderer, nSeries, getColors(nSeries, colors));
} else if (plot instanceof XYPlot) {
final XYItemRenderer renderer = ((XYPlot) plot).getRenderer();
final int nSeries = ((XYPlot) plot).getDataset().getSeriesCount();
setDatasetColors(renderer, nSeries, getColors(nSeries, colors));
}
}
/**
* (Re)colors existing dataset series
*
* @param colorTable The colorTable used to recolor series
*/
public void setColors(final ColorTable colorTable) {
final Plot plot = getChart().getPlot();
if (plot instanceof CategoryPlot) {
final CategoryItemRenderer renderer = ((CategoryPlot) plot).getRenderer();
final int nSeries = ((CategoryPlot) plot).getDataset().getRowCount();
setDatasetColors(renderer, nSeries, getColors(nSeries, colorTable));
} else if (plot instanceof XYPlot) {
final XYItemRenderer renderer = ((XYPlot) plot).getRenderer();
final int nSeries = ((XYPlot) plot).getDataset().getSeriesCount();
setDatasetColors(renderer, nSeries, getColors(nSeries, colorTable));
}
}
public void setChartTitle(final String title) {
try {
super.getChart().setTitle(title);
} catch (final NullPointerException ignored) {
//ignored
}
}
/**
* Replaces the current chart with the specified instance
*
* @param other the instance replacing current contents
*/
public void replace(final SNTChart other) {
setChart(other.getChart());
}
private void setDatasetColors(CategoryItemRenderer renderer, int nSeries, Color[] colors) {
for (int series = 0; series < nSeries; series++) {
renderer.setSeriesPaint(series, colors[series]);
renderer.setSeriesOutlinePaint(series, colors[series]);
renderer.setSeriesItemLabelPaint(series, colors[series]);
}
}
private void setDatasetColors(XYItemRenderer renderer, int nSeries, Color[] colors) {
for (int series = 0; series < nSeries; series++) {
renderer.setSeriesPaint(series, colors[series]);
renderer.setSeriesOutlinePaint(series, colors[series]);
renderer.setSeriesItemLabelPaint(series, colors[series]);
}
}
private Color[] getColors(final int n, final String... colors) {
final Color[] baseColors = new Color[colors.length];
for (int i = 0; i < colors.length; i++) {
final ColorRGB crgb = Colors.getColor(colors[i]);
baseColors[i] = new Color(crgb.getRed(), crgb.getGreen(), crgb.getBlue());
}
if (n < baseColors.length) {
return Arrays.copyOfRange(baseColors, 0, n);
}
final Color[] paddedColors = Arrays.copyOf(baseColors, n);
for (int last = baseColors.length; last != 0 && last < n; last <<= 1) {
System.arraycopy(paddedColors, 0, paddedColors, last, Math.min(last << 1, n) - last);
}
return paddedColors;
}
private Color[] getColors(final int n, final ColorTable colortable) {
final Color[] colors = new Color[n];
for (int i = 0; i < n; i++) {
final int idx = (int) Math.round((float) ((colortable.getLength() - 1) * i) / n);
colors[i] = new Color(colortable.get(ColorTable.RED, idx), colortable.get(ColorTable.GREEN, idx),
colortable.get(ColorTable.BLUE, idx));
}
return colors;
}
/**
* Sets the font size to all components of this chart.
*
* @param size the new font size
*/
public void setFontSize(final float size) {
setFontSize(size, "axis");
setFontSize(size, "labels");
setFontSize(size, "legend");
getChart().getPlot()
.setNoDataMessageFont(getChart().getPlot().getNoDataMessageFont().deriveFont(size));
}
/**
* Sets the font size for this chart.
*
* @param size the new font size
* @param scope which components should be modified. Either "axes", "legends",
* or "labels" (singular/plural allowed)
*/
public void setFontSize(final float size, final String scope) {
switch(scope.toLowerCase()) {
case "axis":
case "axes":
case "ticks":
if (getChart().getPlot() instanceof XYPlot) {
if (getXYPlot().getDomainAxis() != null) {
final Font font = getXYPlot().getDomainAxis().getTickLabelFont().deriveFont(size);
getXYPlot().getDomainAxis().setTickLabelFont(font);
getXYPlot().getDomainAxis().setLabelFont(font);
}
if (getXYPlot().getRangeAxis() != null) {
final Font font = getXYPlot().getRangeAxis().getTickLabelFont().deriveFont(size);
getXYPlot().getRangeAxis().setTickLabelFont(font);
getXYPlot().getRangeAxis().setLabelFont(font);
}
}
else if (getChart().getPlot() instanceof CategoryPlot) {
Font font = getCategoryPlot().getDomainAxis().getTickLabelFont().deriveFont(size);
getCategoryPlot().getDomainAxis().setTickLabelFont(font);
font = getCategoryPlot().getRangeAxis().getTickLabelFont().deriveFont(size);
getCategoryPlot().getRangeAxis().setTickLabelFont(font);
getCategoryPlot().getDomainAxis().setLabelFont(font);
getCategoryPlot().getRangeAxis().setLabelFont(font);
}
else if (getChart().getPlot() instanceof PolarPlot) {
final PolarPlot plot = (PolarPlot)getChart().getPlot();
for (int i = 0; i < plot.getAxisCount(); i++) {
final Font font = plot.getAxis(i).getTickLabelFont().deriveFont(size);
plot.getAxis(i).setTickLabelFont(font);
}
plot.setAngleLabelFont(plot.getAngleLabelFont().deriveFont(size));
}
break;
case "legend":
case "legends":
case "subtitle":
case "subtitles":
final LegendTitle legend = getChart().getLegend();
if (legend != null)
legend.setItemFont(legend.getItemFont().deriveFont(size));
for (int i = 0; i < getChart().getSubtitleCount(); i++) {
final Title title = getChart().getSubtitle(i);
if (title instanceof PaintScaleLegend) {
final PaintScaleLegend lt = (PaintScaleLegend) title;
lt.getAxis().setLabelFont(lt.getAxis().getLabelFont().deriveFont(size));
lt.getAxis().setTickLabelFont(lt.getAxis().getTickLabelFont().deriveFont(size));
}
else if (title instanceof TextTitle) {
final TextTitle tt = (TextTitle) title;
tt.setFont(tt.getFont().deriveFont(size));
} else if (title instanceof LegendTitle) {
final LegendTitle lt = (LegendTitle) title;
lt.setItemFont(lt.getItemFont().deriveFont(size));
}
}
break;
default: // labels annotations
if (getChart().getPlot() instanceof XYPlot) {
final List<?> annotations = getXYPlot().getAnnotations();
if (annotations != null) {
for (int i = 0; i < getXYPlot().getAnnotations().size(); i++) {
final XYAnnotation annotation = getXYPlot().getAnnotations().get(i);
if (annotation instanceof XYTextAnnotation) {
((XYTextAnnotation) annotation)
.setFont(((XYTextAnnotation) annotation).getFont().deriveFont(size));
}
}
}
adjustMarkersFont(getXYPlot().getDomainMarkers(Layer.FOREGROUND), size);
adjustMarkersFont(getXYPlot().getDomainMarkers(Layer.BACKGROUND), size);
adjustMarkersFont(getXYPlot().getRangeMarkers(Layer.FOREGROUND), size);
adjustMarkersFont(getXYPlot().getRangeMarkers(Layer.BACKGROUND), size);
}
else if (getChart().getPlot() instanceof CategoryPlot) {
final List<?> annotations = getCategoryPlot().getAnnotations();
if (annotations != null) {
for (Object o : annotations) {
final CategoryAnnotation annotation = (CategoryAnnotation) o;
if (annotation instanceof TextAnnotation) {
((TextAnnotation) annotation)
.setFont(((TextAnnotation) annotation).getFont().deriveFont(size));
}
}
}
adjustMarkersFont(getCategoryPlot().getDomainMarkers(Layer.FOREGROUND), size);
adjustMarkersFont(getCategoryPlot().getDomainMarkers(Layer.BACKGROUND), size);
adjustMarkersFont(getCategoryPlot().getRangeMarkers(Layer.FOREGROUND), size);
adjustMarkersFont(getCategoryPlot().getRangeMarkers(Layer.BACKGROUND), size);
}
else if (isFlowPlot()) {
final FlowPlot plot = (FlowPlot)(getChart().getPlot());
plot.setDefaultNodeLabelFont(plot.getDefaultNodeLabelFont().deriveFont(Font.PLAIN, size));
}
break;
}
}
private int getFontSize(final String scope) {
switch(scope.toLowerCase()) {
case "axis":
case "axes":
case "ticks":
if (getChart().getPlot() instanceof XYPlot)
return getXYPlot().getDomainAxis().getTickLabelFont().getSize();
else if (getChart().getPlot() instanceof CategoryPlot)
return getCategoryPlot().getDomainAxis().getTickLabelFont().getSize();
else if (getChart().getPlot() instanceof PolarPlot)
return ((PolarPlot)getChart().getPlot()).getAxis().getTickLabelFont().getSize();
break;
case "legend":
case "legends":
case "subtitle":
case "subtitles":
final LegendTitle legend = getChart().getLegend();
if (legend != null)
return legend.getItemFont().getSize();
for (int i = 0; i < getChart().getSubtitleCount(); i++) {
final Title title = getChart().getSubtitle(i);
if (title instanceof TextTitle) {
return ((TextTitle) title).getFont().getSize();
} else if (title instanceof LegendTitle) {
return ((LegendTitle) title).getItemFont().getSize();
}
}
break;
default: // labels annotations
if (getChart().getPlot() instanceof XYPlot) {
return getXYPlot().getDomainAxis().getLabelFont().getSize();
}
else if (getChart().getPlot() instanceof CategoryPlot) {
return getCategoryPlot().getDomainAxis().getLabelFont().getSize();
}
}
return getFont().getSize();
}
public ImagePlus getImage() {
return getImages(1f).iterator().next();
}
public List<ImagePlus> getImages(final float scalingFactor) {
final List<ImagePlus> imps = new ArrayList<>();
if (isCombined()) {
int counter = 1;
for (final Component component : getFrame().getContentPane().getComponents()) {
if (component instanceof ChartPanel) {
final ImagePlus imp = getImagePlus((ChartPanel) component, scalingFactor);
if ("SNTChart".equals(imp.getTitle()))
imp.setTitle("Sub-chart " + counter++);
imps.add(imp);
}
}
} else {
final ImagePlus imp = getImagePlus(this, scalingFactor);
if ("SNTChart".equals(imp.getTitle()))
imp.setTitle(getTitle());
imps.add(imp);
}
return imps;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
private static ImagePlus getImagePlus(final ChartPanel cp, final float scalingFactor) {
final ImagePlus imp = ij.IJ.createImage(
(cp.getChart().getTitle() == null) ? "SNTChart" : cp.getChart().getTitle().getText(), "RGB",
(int) scalingFactor * cp.getWidth(), (int) scalingFactor * cp.getHeight(), 1);
final java.awt.image.BufferedImage image = imp.getBufferedImage();
cp.getChart().draw(image.createGraphics(),
new java.awt.geom.Rectangle2D.Float(0, 0, imp.getWidth(), imp.getHeight()));
imp.setImage(image);
return imp;
}
public void saveAsPNG(final File file) throws IOException {
final int SCALE = 1;
if (isCombined()) {
for (Component c : getFrame().getContentPane().getComponents()) {
if (c instanceof ChartPanel) {
ChartUtils.saveChartAsPNG(SNTUtils.getUniquelySuffixedFile(file), ((ChartPanel) c).getChart(),
((ChartPanel) c).getWidth() * SCALE, ((ChartPanel) c).getHeight() * SCALE);
}
}
} else {
ChartUtils.saveChartAsPNG(file, getChart(), getWidth() * SCALE,
getHeight() * SCALE);
}
}
public void saveAsPNG(final String filePath) throws IOException {
final File f = new File((filePath.toLowerCase().endsWith(".png")) ? filePath : filePath + ".png");
if(!f.getParentFile().exists()) f.getParentFile().mkdirs();
saveAsPNG(f);
}
private void adjustMarkersFont(final Collection<?> markers, final float size) {
if (markers != null) {
markers.forEach(marker -> {
((Marker) marker).setLabelFont(((Marker) marker).getLabelFont().deriveFont(size));
});
}
}
private void replaceBackground(final Color oldColor, final Color newColor) {
if (this.getBackground() == oldColor)
this.setBackground(newColor);
if (getBackground() == oldColor)
setBackground(newColor);
if (getChart().getBackgroundPaint() == oldColor)
getChart().setBackgroundPaint(newColor);
final LegendTitle legend = getChart().getLegend();
if (legend != null && legend.getBackgroundPaint() == oldColor) {
legend.setBackgroundPaint(newColor);
}
for (int i = 0; i < getChart().getSubtitleCount(); i++) {
final Title title = getChart().getSubtitle(i);
if (title instanceof TextTitle) {
final TextTitle tt = (TextTitle) title;
if (tt.getBackgroundPaint() == oldColor)
tt.setBackgroundPaint(newColor);
} else if (title instanceof LegendTitle) {
final LegendTitle lt = (LegendTitle) title;
if (lt.getBackgroundPaint() == oldColor)
lt.setBackgroundPaint(newColor);
}
}
if (getChart().getPlot() instanceof CombinedRangeXYPlot) {
final List<XYPlot> plots = ((CombinedRangeXYPlot)(getChart().getXYPlot())).getSubplots();
for (final XYPlot plot : plots) {
if (plot.getBackgroundPaint() == oldColor)
plot.setBackgroundPaint(newColor);
}
} else if (getChart().getPlot() instanceof XYPlot) {
final XYPlot plot = (XYPlot)(getChart().getPlot());
if (plot.getBackgroundPaint() == oldColor)
plot.setBackgroundPaint(newColor);
} else if (getChart().getPlot() instanceof CategoryPlot) {
final CategoryPlot plot = (getChart().getCategoryPlot());
if (plot.getBackgroundPaint() == oldColor)
plot.setBackgroundPaint(newColor);
} else if (getChart().getPlot() instanceof PolarPlot) {
final PolarPlot plot = (PolarPlot)(getChart().getPlot());
if (plot.getBackgroundPaint() == oldColor)
plot.setBackgroundPaint(newColor);
} else if (isFlowPlot()) {
final FlowPlot plot = (FlowPlot)(getChart().getPlot());
if (plot.getBackgroundPaint() == oldColor)
plot.setBackgroundPaint(newColor);
}
}
private void replaceForegroundColor(final Color oldColor, final Color newColor) {
if (this.getForeground() == oldColor)
this.setForeground(newColor);
if (getForeground() == oldColor)
setForeground(newColor);
if (getChart().getBorderPaint() == oldColor)
getChart().setBorderPaint(newColor);
if (getChart().getTitle() != null)
getChart().getTitle().setPaint(newColor);
final LegendTitle legend = getChart().getLegend();
if (legend != null && legend.getItemPaint() == oldColor) {
legend.setItemPaint(newColor);
}
for (int i = 0; i < getChart().getSubtitleCount(); i++) {
final Title title = getChart().getSubtitle(i);
if (title instanceof TextTitle) {
((TextTitle) title).setPaint(newColor);
} else if (title instanceof LegendTitle) {
((LegendTitle) title).setItemPaint(newColor);
} else if (title instanceof PaintScaleLegend) {
((PaintScaleLegend) title).setStripOutlinePaint(newColor);
((PaintScaleLegend) title).getAxis().setAxisLinePaint(newColor);
((PaintScaleLegend) title).getAxis().setLabelPaint(newColor);
((PaintScaleLegend) title).getAxis().setTickMarkPaint(newColor);
((PaintScaleLegend) title).getAxis().setTickLabelPaint(newColor);
}
}
if (getChart().getPlot() instanceof CombinedRangeXYPlot) {
final CombinedRangeXYPlot comb = (CombinedRangeXYPlot) (getChart().getPlot());
comb.getSubplots().forEach( plot -> replaceForegroundColorOfXYPlot(plot, oldColor, newColor));
} else if (getChart().getPlot() instanceof XYPlot) {
final XYPlot plot = (XYPlot)(getChart().getPlot());
replaceForegroundColorOfXYPlot(plot, oldColor, newColor);
} else if (getChart().getPlot() instanceof CategoryPlot) {
final CategoryPlot plot = (getChart().getCategoryPlot());
for (int i = 0; i < plot.getDomainAxisCount() ; i++)
setForegroundColor(plot.getDomainAxis(i), newColor);
for (int i = 0; i < plot.getRangeAxisCount() ; i++)
setForegroundColor(plot.getRangeAxis(i), newColor);
for (int i = 0; i < plot.getRendererCount(); i++) {
replaceForegroundColor(plot.getRenderer(i), oldColor, newColor);
replaceSeriesColor(plot.getRenderer(i), oldColor, newColor);
}
} else if (getChart().getPlot() instanceof PolarPlot) {
final PolarPlot plot = (PolarPlot)(getChart().getPlot());
for (int i = 0; i < plot.getAxisCount(); i++)
setForegroundColor(plot.getAxis(i), newColor);
plot.setAngleGridlinePaint(newColor);
plot.setAngleLabelPaint(newColor);
final DefaultPolarItemRenderer render = (DefaultPolarItemRenderer) plot.getRenderer();
for (int series = 0; series < plot.getDatasetCount(); series++) {
if (render.getSeriesOutlinePaint(series) == oldColor)
render.setSeriesOutlinePaint(series, newColor);
if (render.getSeriesPaint(series) == oldColor)
render.setSeriesPaint(series, newColor);
}
} else if (isFlowPlot()) {
final FlowPlot plot = (FlowPlot)(getChart().getPlot());
plot.setOutlinePaint(newColor);
plot.setDefaultNodeLabelPaint(newColor);
}
}
private void replaceForegroundColorOfXYPlot(final XYPlot plot, final Color oldColor, final Color newColor) {
for (int i = 0; i < plot.getDomainAxisCount() ; i++)
setForegroundColor(plot.getDomainAxis(i), newColor);
for (int i = 0; i < plot.getRangeAxisCount() ; i++)
setForegroundColor(plot.getRangeAxis(i), newColor);
for (int i = 0; i < plot.getRendererCount(); i++) {
replaceForegroundColor(plot.getRenderer(i), oldColor, newColor);
replaceSeriesColor(plot.getRenderer(i), oldColor, newColor);
}
}
private void replaceForegroundColor(final LegendItemSource render, final Color oldColor, final Color newColor) {
if (render == null) return;
for (int i = 0; i < render.getLegendItems().getItemCount(); i++) {
final LegendItem item = render.getLegendItems().get(i);
item.setLabelPaint(newColor);
if (item.getFillPaint() == oldColor)
item.setFillPaint(newColor);
if (item.getLinePaint() == oldColor)
item.setLinePaint(newColor);
if (item.getOutlinePaint() == oldColor)
item.setOutlinePaint(newColor);
}
if (render instanceof AbstractRenderer) {
final AbstractRenderer rndr = ((AbstractRenderer)render);
rndr.setDefaultItemLabelPaint(newColor);
rndr.setDefaultLegendTextPaint(newColor);
if (rndr.getDefaultFillPaint() == oldColor)
rndr.setDefaultFillPaint(newColor);
if (rndr.getDefaultOutlinePaint() == oldColor)
rndr.setDefaultOutlinePaint(newColor);
}
if (render instanceof AbstractCategoryItemRenderer) {
final AbstractCategoryItemRenderer rndr = ((AbstractCategoryItemRenderer)render);
for (int series = 0; series < rndr.getRowCount(); series++) {
if (rndr.getSeriesFillPaint(series) == oldColor)
rndr.setSeriesFillPaint(series, newColor);
if (rndr.getSeriesOutlinePaint(series) == oldColor)
rndr.setSeriesOutlinePaint(series, newColor);
if (rndr.getSeriesItemLabelPaint(series) == oldColor)
rndr.setSeriesItemLabelPaint(series, newColor);
}
}
if (render instanceof BoxAndWhiskerRenderer)
((BoxAndWhiskerRenderer)render).setArtifactPaint(newColor);
}
private void replaceSeriesColor(final CategoryItemRenderer renderer, final Color oldColor, final Color newColor) {
final int nSeries = renderer.getPlot().getDataset().getRowCount();
for (int series = 0; series < nSeries; series++) {
if (renderer.getSeriesFillPaint(series) == oldColor)
renderer.setSeriesFillPaint(series, newColor);
if (renderer.getSeriesOutlinePaint(series) == oldColor)
renderer.setSeriesOutlinePaint(series, newColor);
if (renderer.getSeriesItemLabelPaint(series) == oldColor)
renderer.setSeriesItemLabelPaint(series, newColor);
}
}
private void replaceSeriesColor(final XYItemRenderer renderer, final Color oldColor, final Color newColor) {
if (renderer != null) {
final int nSeries = renderer.getPlot().getDataset().getSeriesCount();
for (int series = 0; series < nSeries; series++) {
if (renderer.getSeriesFillPaint(series) == oldColor)
renderer.setSeriesFillPaint(series, newColor);
if (renderer.getSeriesOutlinePaint(series) == oldColor)
renderer.setSeriesOutlinePaint(series, newColor);
if (renderer.getSeriesItemLabelPaint(series) == oldColor)
renderer.setSeriesItemLabelPaint(series, newColor);
}
}
}
private void setForegroundColor(final Axis axis, final Color newColor) {
if (axis != null) {
axis.setAxisLinePaint(newColor);
axis.setLabelPaint(newColor);
axis.setTickLabelPaint(newColor);
axis.setTickMarkPaint(newColor);
}
}
private Color getColorFromString(final String string) {
if (string == null) return Color.BLACK;
final ColorRGB c = new ColorRGB(string);
return new Color(c.getRed(), c.getGreen(), c.getBlue());
}
public void applyStyle(final SNTChart template) {
// misc
setPreferredSize(template.getPreferredSize());
setSize(template.getSize());
setGridlinesVisible(template.isGridlinesVisible());
setOutlineVisible(template.isOutlineVisible());
// colors (non-exhaustive)
setBackground(template.getBackground());
setForeground(template.getForeground());
setBackground(template.getBackground());
setForeground(template.getForeground());
getChart().setBackgroundPaint(template.getChart().getBackgroundPaint());
getChart().setBorderPaint(template.getChart().getBorderPaint());
if (getChart().getLegend() != null && template.getChart().getLegend() != null) {
getChart().getLegend().setBackgroundPaint(template.getChart().getLegend().getBackgroundPaint());
getChart().getLegend().setItemPaint(template.getChart().getLegend().getItemPaint());
}
getChart().getPlot().setBackgroundPaint(template.getChart().getPlot().getBackgroundPaint());
getChart().getPlot().setOutlinePaint(template.getChart().getPlot().getOutlinePaint());
getChart().getPlot().setNoDataMessagePaint(template.getChart().getPlot().getNoDataMessagePaint());
setZoomOutlinePaint(template.getZoomOutlinePaint());
setZoomFillPaint(template.getZoomFillPaint());
if (getChart().getPlot() instanceof XYPlot && template.getChart().getPlot() instanceof XYPlot) {
final XYPlot plot = (XYPlot)(getChart().getPlot());
final XYPlot tPlot = (XYPlot)(template.getChart().getPlot());
if (tPlot.getDomainAxis().getAxisLinePaint() instanceof Color)
setForegroundColor(plot.getDomainAxis(), (Color)tPlot.getDomainAxis().getAxisLinePaint());
if (tPlot.getRangeAxis().getAxisLinePaint() instanceof Color)
setForegroundColor(plot.getRangeAxis(), (Color)tPlot.getRangeAxis().getAxisLinePaint());
} else if (getChart().getPlot() instanceof CategoryPlot) {
final CategoryPlot plot = getChart().getCategoryPlot();
final CategoryPlot tPlot = (CategoryPlot)(template.getChart().getPlot());
if (tPlot.getDomainAxis().getAxisLinePaint() instanceof Color)
setForegroundColor(plot.getDomainAxis(), (Color)tPlot.getDomainAxis().getAxisLinePaint());
if (tPlot.getRangeAxis().getAxisLinePaint() instanceof Color)
setForegroundColor(plot.getRangeAxis(), (Color)tPlot.getRangeAxis().getAxisLinePaint());
}
// fonts
setFontSize(template.getFontSize("axis"), "axis");
setFontSize(template.getFontSize("labels"), "labels");
setFontSize(template.getFontSize("legend"), "legend");
getChart().getPlot()
.setNoDataMessageFont(template.getChart().getPlot().getNoDataMessageFont());
}
public void addPolygon(final Polygon2D poly, final String lineColor, final String fillColor) {
final ColorRGB lColor = (lineColor == null || lineColor.isBlank()) ? null : ColorRGB.fromHTMLColor(lineColor);
final ColorRGB fColor = (fillColor == null || fillColor.isBlank()) ? null : ColorRGB.fromHTMLColor(fillColor);
addPolygon(poly, lColor, fColor);
}
public void addPolygon(final Polygon2D poly, final ColorRGB lineColor, final ColorRGB fillColor) {
final double[] cc = new double[poly.numVertices() * 2];
int counter =0;
for (int i = 0; i < poly.numVertices(); i++) {
cc[counter++] = poly.vertex(i).getDoublePosition(0);
cc[counter++] = poly.vertex(i).getDoublePosition(1);
}
final Stroke lineStroke = (lineColor == null) ? null : new BasicStroke(1f);
final Color lColor = (lineColor == null) ? null :
SNTColor.alphaColor(new Color(lineColor.getRed(), lineColor.getGreen(), lineColor.getBlue()), 50);
final Color fColor = (fillColor == null) ? null :
SNTColor.alphaColor(new Color(fillColor.getRed(), fillColor.getGreen(), fillColor.getBlue()), 25);
final XYPolygonAnnotation annot = new XYPolygonAnnotation(cc, lineStroke, lColor, fColor);
//annot.setToolTipText("Polygon2D");
getXYPlot().getRenderer().addAnnotation(annot);
}
/**
* Adds a subtitle to the chart.
*
* @param label the subtitle text
*/
public void annotate(final String label) {
annotate(label, null, "center");
}
/**
* Adds a subtitle to the chart.
*
* @param label the subtitle text
* @param tooltip the tooltip text. {@code null} permitted
* @param alignment either 'left', 'center', or 'right'
*/
public void annotate(final String label, final String tooltip, final String alignment) {
final TextTitle tLabel = new TextTitle(label);
tLabel.setFont(tLabel.getFont().deriveFont(Font.PLAIN, getFontSize("legend")));
tLabel.setPosition(RectangleEdge.BOTTOM);
tLabel.setToolTipText(tooltip);
switch (alignment.toLowerCase()) {
case "left":
tLabel.setHorizontalAlignment(HorizontalAlignment.LEFT);
tLabel.setTextAlignment(HorizontalAlignment.LEFT);
break;
case "right":
tLabel.setHorizontalAlignment(HorizontalAlignment.RIGHT);
tLabel.setTextAlignment(HorizontalAlignment.RIGHT);
break;
default:
tLabel.setHorizontalAlignment(HorizontalAlignment.CENTER);
tLabel.setTextAlignment(HorizontalAlignment.CENTER);
}
getChart().addSubtitle(tLabel);
}
/**
* Highlights a point in a histogram/XY plot by drawing a labeled arrow at the
* specified location.
*
* @param x the x-coordinate