Java Examples for org.jfree.ui.TextAnchor
The following java examples will help you to understand the usage of org.jfree.ui.TextAnchor. These source code samples are taken from different open source projects.
Example 1
| Project: radargun-master File: TimelineChart.java View source code |
public void setEvents(List<? extends Object> events, int slaveIndex, long startTimestamp, long endTimestamp, double lowerBound, double upperBound) {
int paintIndex = slaveIndex % DEFAULT_PAINTS.length;
if (paintIndex < 0)
paintIndex += DEFAULT_PAINTS.length;
paint = DEFAULT_PAINTS[paintIndex];
this.startTimestamp = startTimestamp;
this.endTimestamp = endTimestamp + (startTimestamp == endTimestamp ? 1 : 0);
TimeSeries series = new TimeSeries("Slave " + slaveIndex);
TimeSeriesCollection dataset = new TimeSeriesCollection(series, GMT);
chart = ChartFactory.createTimeSeriesChart(null, "Time from start", null, dataset, false, false, false);
chart.setBackgroundPaint(new Color(0, 0, 0, 0));
XYPlot plot = chart.getXYPlot();
plot.getRenderer().setSeriesPaint(0, paint);
plot.setBackgroundAlpha(0);
plot.setDomainGridlinesVisible(false);
plot.setDomainZeroBaselineVisible(true);
plot.setRangeGridlinesVisible(false);
plot.setRangeZeroBaselineVisible(true);
Number[] minValues = new Number[MAX_EVENT_VALUES];
Number[] maxValues = new Number[MAX_EVENT_VALUES];
long[] minTimestamps = new long[MAX_EVENT_VALUES];
long[] maxTimestamps = new long[MAX_EVENT_VALUES];
for (Object event : events) {
if (event instanceof Timeline.Value) {
Timeline.Value value = (Timeline.Value) event;
if (value.timestamp > this.endTimestamp) {
throw new IllegalStateException(String.format("Current timestamp %d is bigger then end timestamp %d", value.timestamp, this.endTimestamp));
}
int bucket = (int) ((value.timestamp - startTimestamp) * (MAX_EVENT_VALUES - 1) / (this.endTimestamp - startTimestamp));
if (minValues[bucket] == null) {
minValues[bucket] = value.value;
maxValues[bucket] = value.value;
minTimestamps[bucket] = value.timestamp;
maxTimestamps[bucket] = value.timestamp;
} else {
if (minValues[bucket].doubleValue() > value.value.doubleValue()) {
minValues[bucket] = value.value;
}
if (maxValues[bucket].doubleValue() < value.value.doubleValue()) {
maxValues[bucket] = value.value;
}
minTimestamps[bucket] = Math.min(minTimestamps[bucket], value.timestamp);
maxTimestamps[bucket] = Math.max(maxTimestamps[bucket], value.timestamp);
}
} else if (event instanceof Timeline.IntervalEvent) {
Timeline.IntervalEvent intervalEvent = (Timeline.IntervalEvent) event;
IntervalMarker marker = new IntervalMarker(intervalEvent.timestamp - startTimestamp, intervalEvent.timestamp + intervalEvent.duration - startTimestamp, paint, stroke, paint, stroke, 0.3f);
marker.setLabel(intervalEvent.description);
marker.setLabelAnchor(RectangleAnchor.BOTTOM);
marker.setLabelTextAnchor(TextAnchor.BOTTOM_CENTER);
marker.setLabelOffset(new RectangleInsets(0, 0, (slaveIndex + 1) * LABEL_OFFSET, 0));
plot.addDomainMarker(marker);
} else if (event instanceof Timeline.TextEvent) {
Timeline.TextEvent textEvent = (Timeline.TextEvent) event;
ValueMarker marker = new ValueMarker(textEvent.timestamp - startTimestamp, paint, stroke);
marker.setLabel(textEvent.text);
marker.setLabelAnchor(RectangleAnchor.BOTTOM_LEFT);
marker.setLabelTextAnchor(TextAnchor.BOTTOM_LEFT);
marker.setLabelOffset(new RectangleInsets(0, 0, (slaveIndex + 1) * LABEL_OFFSET, 0));
plot.addDomainMarker(marker);
}
}
for (int bucket = 0; bucket < MAX_EVENT_VALUES; ++bucket) {
if (minValues[bucket] == null)
continue;
series.addOrUpdate(time(minTimestamps[bucket] - startTimestamp), minValues[bucket]);
series.addOrUpdate(time(maxTimestamps[bucket] - startTimestamp), maxValues[bucket]);
}
DateAxis dateAxis = (DateAxis) plot.getDomainAxis();
dateAxis.setTimeZone(GMT);
dateAxis.setMinimumDate(new Date(0));
dateAxis.setMaximumDate(new Date(endTimestamp - startTimestamp));
if (upperBound > lowerBound) {
plot.getRangeAxis().setRange(lowerBound, upperBound);
}
}Example 2
| Project: bonita-simulation-master File: BarChartVisibleBarLabel.java View source code |
/* (non-Javadoc)
* @see net.sf.jasperreports.engine.JRChartCustomizer#customize(org.jfree.chart.JFreeChart, net.sf.jasperreports.engine.JRChart)
*/
public void customize(JFreeChart chart, JRChart jasperChart) {
BarRenderer bsr = (BarRenderer) chart.getCategoryPlot().getRenderer();
bsr.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());
bsr.setItemLabelsVisible(true);
// Set position of Items label : center
bsr.setPositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER));
bsr.setNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER));
// If there isn't enough space to draw the ItemLabel...
bsr.setPositiveItemLabelPositionFallback(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER));
bsr.setNegativeItemLabelPositionFallback(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER));
}Example 3
| Project: cooper-master File: SplineChartCreater.java View source code |
private JFreeChart createChart(final GraphDataItem item) {
JFreeChart jfreechart = ChartFactory.createXYLineChart(item.getTitle(), item.getLineXName(), item.getLineYName(), this.createData(item), PlotOrientation.VERTICAL, true, true, true);
Font font = new Font("宋体", Font.PLAIN, 13);
jfreechart.getTitle().setFont(font);
jfreechart.getLegend().setItemFont(font);
jfreechart.getXYPlot().getDomainAxis().setTickLabelFont(font);
jfreechart.getXYPlot().getDomainAxis().setLabelFont(font);
jfreechart.getXYPlot().getRangeAxis().setTickLabelFont(font);
jfreechart.getXYPlot().getRangeAxis().setLabelFont(font);
jfreechart.getXYPlot().setBackgroundPaint(ChartColor.WHITE);
XYPlot xyplot = (XYPlot) jfreechart.getPlot();
xyplot.setDomainPannable(true);
xyplot.setRangePannable(true);
if (item.getBgColordData() != null) {
for (RegionColor region : item.getBgColordData().getData()) {
IntervalMarker intervalmarker = new IntervalMarker(region.begin, region.end);
intervalmarker.setLabel(region.title);
intervalmarker.setLabelFont(new Font("宋体", 2, 11));
intervalmarker.setLabelAnchor(RectangleAnchor.RIGHT);
intervalmarker.setLabelTextAnchor(TextAnchor.CENTER_RIGHT);
intervalmarker.setPaint(region.color);
xyplot.addRangeMarker(intervalmarker, Layer.BACKGROUND);
}
}
XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyplot.getRenderer();
xylineandshaperenderer.setBaseShapesVisible(true);
xylineandshaperenderer.setBaseShapesFilled(true);
xylineandshaperenderer.setDrawOutlines(true);
xylineandshaperenderer.setUseFillPaint(true);
xylineandshaperenderer.setBaseFillPaint(Color.white);
xylineandshaperenderer.setSeriesStroke(0, new BasicStroke(3F));
xylineandshaperenderer.setSeriesOutlineStroke(0, new BasicStroke(2.0F));
xylineandshaperenderer.setSeriesShape(0, new java.awt.geom.Ellipse2D.Double(-5D, -5D, 10D, 10D));
xylineandshaperenderer.setBaseItemLabelFont(new Font("宋体", 2, 11));
if (item.getFgColorData() != null) {
xylineandshaperenderer.setSeriesPaint(0, item.getFgColorData().mainColor);
}
final List<Object> values = new ArrayList<Object>();
for (Object name : item.getDatas().keySet()) {
values.add(name);
}
XYToolTipGenerator generator = new CustomXYToolTipGenerator() {
@Override
public String generateToolTip(XYDataset data, int series, int i) {
return item.getTip(values.get(i));
}
};
xylineandshaperenderer.setBaseToolTipGenerator(generator);
xylineandshaperenderer.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator() {
@Override
public String generateLabel(XYDataset dataset, int series, int i) {
return item.getTip(values.get(i));
}
});
xylineandshaperenderer.setBaseItemLabelsVisible(true);
return jfreechart;
}Example 4
| Project: ismp_manager-master File: ReportAction.java View source code |
/**
* 风险评估分�报告
*/
@SuppressWarnings("deprecation")
public ActionForward assessmentAnalysisReport(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
AsseInfoProj asseInfoProj = loadAsseInfoproj(request);
Map reportMap = reportService.assessmentAnalysisReport(asseInfoProj);
//饼状图所需数�
Long HighRiskNum = (Long) reportMap.get("HighRiskNum");
Long MiddRiskNum = (Long) reportMap.get("MiddRiskNum");
Long LowRiskNum = (Long) reportMap.get("LowRiskNum");
DefaultPieDataset dataSet = new DefaultPieDataset();
dataSet.setValue("高风险点", HighRiskNum.doubleValue());
dataSet.setValue("ä¸é£Žé™©ç‚¹", MiddRiskNum.doubleValue());
dataSet.setValue("低风险点", LowRiskNum.doubleValue());
JFreeChart chart = ChartFactory.createPieChart3D("ä¸?å?Œé£Žé™©ç‰çº§çš„æ•°é‡?统计", dataSet, true, true, false);
chart.getTitle().setFont(new Font("宋体", Font.PLAIN, 18));
//获�图表区域对象
PiePlot piePlot = (PiePlot) chart.getPlot();
piePlot.setLabelFont(new Font("宋体", Font.BOLD, 12));
chart.getLegend().setItemFont(new Font("宋体", 0, 12));
PiePlot3D piePlot3D = (PiePlot3D) chart.getPlot();
piePlot3D.setStartAngle(150D);
piePlot3D.setDirection(Rotation.CLOCKWISE);
piePlot3D.setForegroundAlpha(0.5F);
piePlot3D.setNoDataMessage("æ— æ•°æ?®æ˜¾ç¤º");
piePlot3D.setCircular(true);
piePlot3D.setLabelFont(new Font("宋体", 0, 18));
piePlot3D.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}有{1}个 å? {2}", NumberFormat.getNumberInstance(), new DecimalFormat("0.00%")));
String filename = ServletUtilities.saveChartAsPNG(chart, 700, 400, null, request.getSession());
String graphURL = request.getContextPath() + "/DisplayChart?filename=" + filename;
request.setAttribute("graphURL", graphURL);
request.setAttribute("filename", filename);
//柱状图所需数�
double[][] asseData = (double[][]) reportMap.get("asseData");
String[] asseDataRowKeys = (String[]) reportMap.get("asseDataRowKeys");
String[] asseDataColumnKeys = (String[]) reportMap.get("asseDataColumnKeys");
CategoryDataset dataset1 = DatasetUtilities.createCategoryDataset(asseDataRowKeys, asseDataColumnKeys, asseData);
JFreeChart chart1 = ChartFactory.createBarChart3D("é‡?è¦?资产的ä¸?å?Œç‰çº§é£Žé™©ç»Ÿè®¡", "风险", "风险数目", dataset1, PlotOrientation.VERTICAL, true, true, false);
CategoryPlot plot = chart1.getCategoryPlot();
CategoryAxis domainAxis = plot.getDomainAxis();
NumberAxis numberaxis = (NumberAxis) plot.getRangeAxis();
TextTitle textTitle = chart1.getTitle();
textTitle.setFont(new Font("宋体", Font.PLAIN, 18));
domainAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 11));
domainAxis.setLabelFont(new Font("宋体", Font.PLAIN, 12));
numberaxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 12));
numberaxis.setLabelFont(new Font("黑体", Font.PLAIN, 12));
chart1.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12));
//è®¾ç½®ç½‘æ ¼èƒŒæ™¯é¢œè‰²
plot.setBackgroundPaint(Color.white);
//è®¾ç½®ç½‘æ ¼ç«–çº¿é¢œè‰²
plot.setDomainGridlinePaint(Color.pink);
//è®¾ç½®ç½‘æ ¼æ¨ªçº¿é¢œè‰²
plot.setRangeGridlinePaint(Color.pink);
Font font = new Font("宋体", 0, 16);
plot.getDomainAxis().setLabelFont(font);
plot.getDomainAxis().setTickLabelFont(font);
plot.getRangeAxis().setLabelFont(font);
plot.getRangeAxis().setTickLabelFont(font);
//显示æ¯?个柱的数值,并修改该数值的å—体属性
BarRenderer3D renderer = new BarRenderer3D();
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
renderer.setBaseItemLabelsVisible(true);
//é»˜è®¤çš„æ•°å—æ˜¾ç¤ºåœ¨æŸ±å?ä¸ï¼Œé€šè¿‡å¦‚下两å?¥å?¯è°ƒæ•´æ•°å—的显示
//注æ„?:æ¤å?¥å¾ˆå…³é”®ï¼Œè‹¥æ— æ¤å?¥ï¼Œé‚£æ•°å—çš„æ˜¾ç¤ºä¼šè¢«è¦†ç›–ï¼Œç»™äººæ•°å—æ²¡æœ‰æ˜¾ç¤ºå‡ºæ?¥çš„问题
renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
renderer.setItemLabelAnchorOffset(10D);
//设置�个地区所包�的平行柱的之间�离
renderer.setItemMargin(0.3);
renderer.setItemLabelFont(new Font("宋体", Font.BOLD, 12));
plot.setRenderer(renderer);
plot.setDomainAxisLocation(AxisLocation.TOP_OR_RIGHT);
plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
String filename1 = ServletUtilities.saveChartAsPNG(chart1, 700, 400, null, request.getSession());
String graphURL1 = request.getContextPath() + "/DisplayChart?filename=" + filename1;
request.setAttribute("graphURL1", graphURL1);
request.setAttribute("filename1", filename1);
//�资产的风险列表
List repoList = (List) reportMap.get("repoList");
request.setAttribute("repoList", repoList);
List dicSecuLeveList = dicSecuLeveService.findAll();
request.setAttribute("dicSecuLeveList", dicSecuLeveList);
return mapping.findForward("report7");
}Example 5
| Project: mdrill-master File: PiePlot.java View source code |
/**
* Draws the pie section labels in the simple form.
*
* @param g2 the graphics device.
* @param keys the section keys.
* @param totalValue the total value for all sections in the pie.
* @param plotArea the plot area.
* @param pieArea the area containing the pie.
* @param state the plot state.
*
* @since 1.0.7
*/
protected void drawSimpleLabels(Graphics2D g2, List keys, double totalValue, Rectangle2D plotArea, Rectangle2D pieArea, PiePlotState state) {
Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
RectangleInsets labelInsets = new RectangleInsets(UnitType.RELATIVE, 0.18, 0.18, 0.18, 0.18);
Rectangle2D labelsArea = labelInsets.createInsetRectangle(pieArea);
double runningTotal = 0.0;
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Comparable key = (Comparable) iterator.next();
boolean include = true;
double v = 0.0;
Number n = getDataset().getValue(key);
if (n == null) {
include = !getIgnoreNullValues();
} else {
v = n.doubleValue();
include = getIgnoreZeroValues() ? v > 0.0 : v >= 0.0;
}
if (include) {
runningTotal = runningTotal + v;
// work out the mid angle (0 - 90 and 270 - 360) = right,
// otherwise left
double mid = getStartAngle() + (getDirection().getFactor() * ((runningTotal - v / 2.0) * 360) / totalValue);
Arc2D arc = new Arc2D.Double(labelsArea, getStartAngle(), mid - getStartAngle(), Arc2D.OPEN);
int x = (int) arc.getEndPoint().getX();
int y = (int) arc.getEndPoint().getY();
PieSectionLabelGenerator labelGenerator = getLabelGenerator();
if (labelGenerator == null) {
continue;
}
String label = labelGenerator.generateSectionLabel(this.dataset, key);
if (label == null) {
continue;
}
g2.setFont(this.labelFont);
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtilities.getTextBounds(label, g2, fm);
Rectangle2D out = this.labelPadding.createOutsetRectangle(bounds);
Shape bg = ShapeUtilities.createTranslatedShape(out, x - bounds.getCenterX(), y - bounds.getCenterY());
if (this.labelShadowPaint != null) {
Shape shadow = ShapeUtilities.createTranslatedShape(bg, this.shadowXOffset, this.shadowYOffset);
g2.setPaint(this.labelShadowPaint);
g2.fill(shadow);
}
if (this.labelBackgroundPaint != null) {
g2.setPaint(this.labelBackgroundPaint);
g2.fill(bg);
}
if (this.labelOutlinePaint != null && this.labelOutlineStroke != null) {
g2.setPaint(this.labelOutlinePaint);
g2.setStroke(this.labelOutlineStroke);
g2.draw(bg);
}
g2.setPaint(this.labelPaint);
g2.setFont(this.labelFont);
TextUtilities.drawAlignedString(getLabelGenerator().generateSectionLabel(getDataset(), key), g2, x, y, TextAnchor.CENTER);
}
}
g2.setComposite(originalComposite);
}Example 6
| Project: performance-benchmark-master File: JFreeBarChart.java View source code |
@Override
protected JFreeChart createChart(AbstractDataset dataset) {
JFreeChart chart = ChartFactory.createBarChart("Performance chart", "Bench case", "Time(s)", (DefaultCategoryDataset) dataset, PlotOrientation.VERTICAL, true, true, false);
rotateCategoryAxis(chart, Math.PI / 4.0);
CategoryPlot plot = chart.getCategoryPlot();
BarRenderer renderer = (BarRenderer) plot.getRenderer();
renderer.setItemLabelGenerator(new CategoryItemLabelGenerator() {
public String generateColumnLabel(CategoryDataset dataset, int column) {
return "col" + column;
}
public String generateLabel(CategoryDataset dataset, int row, int column) {
return "" + dataset.getValue(row, column).intValue();
}
public String generateRowLabel(CategoryDataset dataset, int row) {
return "row" + row;
}
});
renderer.setBaseItemLabelPaint(Color.black);
renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.INSIDE12, TextAnchor.CENTER_RIGHT, TextAnchor.CENTER_RIGHT, -Math.PI / 2.0));
renderer.setItemLabelsVisible(true);
return chart;
}Example 7
| Project: SPIM_Registration-master File: MouseListenerTimelapse.java View source code |
protected ValueMarker makeMarker(final int timePoint) {
final ValueMarker valueMarker = new ValueMarker(timePoint);
valueMarker.setStroke(new BasicStroke(1.5f));
valueMarker.setPaint(new Color(0.0f, 93f / 255f, 9f / 255f));
valueMarker.setLabel(" Reference\n Timepoint " + timePoint);
valueMarker.setLabelAnchor(RectangleAnchor.BOTTOM);
valueMarker.setLabelTextAnchor(TextAnchor.BOTTOM_LEFT);
return valueMarker;
}Example 8
| Project: aorra-master File: BeerCoasterV2.java View source code |
private void drawArc(GraphUtils g, float radius, int startAngle, int arcAngle, Condition condition, String label, float labelRadius, int labelAngle, Rotation labelDirection, Color fc, GraphUtils.TextAnchor anchor) {
Stroke stroke = g.getGraphics().getStroke();
g.getGraphics().setColor(getColor(condition));
g.fillArc(bcx, bcy, radius, startAngle, arcAngle);
g.getGraphics().setColor(Color.WHITE);
g.getGraphics().setStroke(new BasicStroke(BORDER_WIDTH));
g.drawArc(bcx, bcy, radius, startAngle, arcAngle);
g.getGraphics().setColor(fc);
g.drawCircleText(label, bcx, bcy, labelRadius, GraphUtils.toRadians(labelAngle), labelDirection == Rotation.CLOCKWISE, anchor);
g.getGraphics().setStroke(stroke);
}Example 9
| Project: ascension-log-visualizer-new-master File: GanttChartBuilder.java View source code |
private void addDayMarkers(final CategoryPlot plot) {
for (final DayChange dc : this.getLogData().getDayChanges()) {
final ValueMarker day = new ValueMarker(dc.getTurnNumber());
day.setLabel("Day " + dc.getDayNumber());
day.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
day.setLabelTextAnchor(TextAnchor.TOP_LEFT);
day.setStroke(new BasicStroke(2));
day.setPaint(Color.BLUE);
plot.addRangeMarker(day);
}
}Example 10
| Project: ATK-master File: Action.java View source code |
/**
* Set Annotation properties used in Analysis Tool (keypress,log,screenshot...)
* For each action a marker and an Annotation is related
* @param Xvalue StartTime of Marker Action
* @param Yvalue Position where to display the comment 1 for the top 0 for the bottom
* @param color Color of Marker
*/
public void setAnnotation(double Xvalue, Paint color) {
if (szActionName != null) {
annotation = new XYTextAnnotation(szActionName, Xvalue, 0.05);
annotation.setFont(new Font("SansSerif", Font.PLAIN, 12));
annotation.setRotationAngle(3 * Math.PI / 2);
annotation.setRotationAnchor(TextAnchor.BOTTOM_LEFT);
annotation.setTextAnchor(TextAnchor.BOTTOM_LEFT);
annotation.setToolTipText(szActionName);
annotation.setPaint(color);
}
}Example 11
| Project: codehaus-mojo-master File: ChartUtil.java View source code |
/**
* Generate a {@link ValueMarker}.
*/
private static ValueMarker addValueMarker(String text, double x, boolean domain) {
ValueMarker marker = new ValueMarker(x);
marker.setPaint(Color.GRAY);
marker.setLabel(text);
if (domain) {
marker.setLabelAnchor(RectangleAnchor.TOP_LEFT);
marker.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
} else {
marker.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
marker.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT);
}
return marker;
}Example 12
| Project: ConcesionariaDB-master File: GenericChartTheme.java View source code |
/**
*
*/
protected JFreeChart createDialChart() throws JRException {
JRMeterPlot jrPlot = (JRMeterPlot) getPlot();
// get data for diagrams
DialPlot dialPlot = new DialPlot();
dialPlot.setDataset((ValueDataset) getDataset());
StandardDialFrame dialFrame = new StandardDialFrame();
dialPlot.setDialFrame(dialFrame);
DialBackground db = new DialBackground(jrPlot.getBackcolor());
dialPlot.setBackground(db);
Range range = convertRange(jrPlot.getDataRange());
//double bound = Math.max(Math.abs(range.getUpperBound()), Math.abs(range.getLowerBound()));
StandardDialScale scale = new StandardDialScale(range.getLowerBound(), range.getUpperBound(), 225, -270, (range.getUpperBound() - range.getLowerBound()) / 6, 15);
scale.setTickRadius(0.9);
scale.setTickLabelOffset(0.16);
JRFont tickLabelFont = jrPlot.getTickLabelFont();
Integer defaultBaseFontSize = (Integer) getDefaultValue(defaultChartPropertiesMap, ChartThemesConstants.BASEFONT_SIZE);
Font themeTickLabelFont = getFont((JRFont) getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_TICK_LABEL_FONT), tickLabelFont, defaultBaseFontSize);
scale.setTickLabelFont(themeTickLabelFont);
scale.setMajorTickStroke(new BasicStroke(1f));
scale.setMinorTickStroke(new BasicStroke(0.3f));
scale.setMajorTickPaint(jrPlot.getTickColor());
scale.setMinorTickPaint(jrPlot.getTickColor());
scale.setTickLabelsVisible(true);
scale.setFirstTickLabelVisible(true);
dialPlot.addScale(0, scale);
List intervals = jrPlot.getIntervals();
if (intervals != null && intervals.size() > 0) {
int size = Math.min(3, intervals.size());
int colorStep = 0;
if (size > 0)
colorStep = 255 / size;
for (int i = 0; i < size; i++) {
JRMeterInterval interval = (JRMeterInterval) intervals.get(i);
Range intervalRange = convertRange(interval.getDataRange());
Color color = new Color(255 - colorStep * i, 0 + colorStep * i, 0);
StandardDialRange dialRange = new StandardDialRange(intervalRange.getLowerBound(), intervalRange.getUpperBound(), interval.getBackgroundColor() == null ? color : interval.getBackgroundColor());
dialRange.setInnerRadius(0.41);
dialRange.setOuterRadius(0.41);
dialPlot.addLayer(dialRange);
}
}
JRValueDisplay display = jrPlot.getValueDisplay();
String displayVisibility = display != null && getChart().hasProperties() ? getChart().getPropertiesMap().getProperty(DefaultChartTheme.PROPERTY_DIAL_VALUE_DISPLAY_VISIBLE) : "false";
if (Boolean.parseBoolean(displayVisibility)) {
DialValueIndicator dvi = new DialValueIndicator(0);
dvi.setBackgroundPaint(ChartThemesConstants.TRANSPARENT_PAINT);
// dvi.setFont(JRFontUtil.getAwtFont(jrFont).deriveFont(10f).deriveFont(Font.BOLD));
dvi.setOutlinePaint(ChartThemesConstants.TRANSPARENT_PAINT);
dvi.setPaint(Color.WHITE);
String pattern = display.getMask() != null ? display.getMask() : "#,##0.####";
if (pattern != null)
dvi.setNumberFormat(new DecimalFormat(pattern));
dvi.setRadius(0.15);
dvi.setValueAnchor(RectangleAnchor.CENTER);
dvi.setTextAnchor(TextAnchor.CENTER);
//dvi.setTemplateValue(Double.valueOf(getDialTickValue(dialPlot.getValue(0),dialUnitScale)));
dialPlot.addLayer(dvi);
}
String label = getChart().hasProperties() ? getChart().getPropertiesMap().getProperty(DefaultChartTheme.PROPERTY_DIAL_LABEL) : null;
if (label != null) {
JRFont displayFont = jrPlot.getValueDisplay().getFont();
Font themeDisplayFont = getFont((JRFont) getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_DISPLAY_FONT), displayFont, defaultBaseFontSize);
String[] textLines = label.split("\\n");
for (int i = 0; i < textLines.length; i++) {
DialTextAnnotation dialAnnotation = new DialTextAnnotation(textLines[i]);
dialAnnotation.setFont(themeDisplayFont);
dialAnnotation.setPaint(jrPlot.getValueDisplay().getColor());
dialAnnotation.setRadius(Math.sin(Math.PI / 4.0) + i / 10.0);
dialAnnotation.setAnchor(TextAnchor.CENTER);
dialPlot.addLayer(dialAnnotation);
}
}
DialPointer needle = new DialPointer.Pointer();
needle.setVisible(true);
needle.setRadius(0.91);
dialPlot.addLayer(needle);
DialCap cap = new DialCap();
cap.setRadius(0.05);
cap.setFillPaint(Color.DARK_GRAY);
cap.setOutlinePaint(Color.GRAY);
cap.setOutlineStroke(new BasicStroke(0.5f));
dialPlot.setCap(cap);
JFreeChart jfreeChart = new JFreeChart((String) evaluateExpression(getChart().getTitleExpression()), null, dialPlot, isShowLegend());
// Set all the generic options
configureChart(jfreeChart, getPlot());
return jfreeChart;
}Example 13
| Project: EvolutionaryMusic-master File: PiePlot.java View source code |
/**
* Draws the pie section labels in the simple form.
*
* @param g2 the graphics device.
* @param keys the section keys.
* @param totalValue the total value for all sections in the pie.
* @param plotArea the plot area.
* @param pieArea the area containing the pie.
* @param state the plot state.
*
* @since 1.0.7
*/
protected void drawSimpleLabels(Graphics2D g2, List keys, double totalValue, Rectangle2D plotArea, Rectangle2D pieArea, PiePlotState state) {
Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
RectangleInsets labelInsets = new RectangleInsets(UnitType.RELATIVE, 0.18, 0.18, 0.18, 0.18);
Rectangle2D labelsArea = labelInsets.createInsetRectangle(pieArea);
double runningTotal = 0.0;
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Comparable key = (Comparable) iterator.next();
boolean include = true;
double v = 0.0;
Number n = getDataset().getValue(key);
if (n == null) {
include = !getIgnoreNullValues();
} else {
v = n.doubleValue();
include = getIgnoreZeroValues() ? v > 0.0 : v >= 0.0;
}
if (include) {
runningTotal = runningTotal + v;
// work out the mid angle (0 - 90 and 270 - 360) = right,
// otherwise left
double mid = getStartAngle() + (getDirection().getFactor() * ((runningTotal - v / 2.0) * 360) / totalValue);
Arc2D arc = new Arc2D.Double(labelsArea, getStartAngle(), mid - getStartAngle(), Arc2D.OPEN);
int x = (int) arc.getEndPoint().getX();
int y = (int) arc.getEndPoint().getY();
PieSectionLabelGenerator labelGenerator = getLabelGenerator();
if (labelGenerator == null) {
continue;
}
String label = labelGenerator.generateSectionLabel(this.dataset, key);
if (label == null) {
continue;
}
g2.setFont(this.labelFont);
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtilities.getTextBounds(label, g2, fm);
Rectangle2D out = this.labelPadding.createOutsetRectangle(bounds);
Shape bg = ShapeUtilities.createTranslatedShape(out, x - bounds.getCenterX(), y - bounds.getCenterY());
if (this.labelShadowPaint != null) {
Shape shadow = ShapeUtilities.createTranslatedShape(bg, this.shadowXOffset, this.shadowYOffset);
g2.setPaint(this.labelShadowPaint);
g2.fill(shadow);
}
if (this.labelBackgroundPaint != null) {
g2.setPaint(this.labelBackgroundPaint);
g2.fill(bg);
}
if (this.labelOutlinePaint != null && this.labelOutlineStroke != null) {
g2.setPaint(this.labelOutlinePaint);
g2.setStroke(this.labelOutlineStroke);
g2.draw(bg);
}
g2.setPaint(this.labelPaint);
g2.setFont(this.labelFont);
TextUtilities.drawAlignedString(getLabelGenerator().generateSectionLabel(getDataset(), key), g2, x, y, TextAnchor.CENTER);
}
}
g2.setComposite(originalComposite);
}Example 14
| Project: HeartRateAdjuster-master File: PiePlot.java View source code |
/**
* Draws the pie section labels in the simple form.
*
* @param g2 the graphics device.
* @param keys the section keys.
* @param totalValue the total value for all sections in the pie.
* @param plotArea the plot area.
* @param pieArea the area containing the pie.
* @param state the plot state.
*
* @since 1.0.7
*/
protected void drawSimpleLabels(Graphics2D g2, List keys, double totalValue, Rectangle2D plotArea, Rectangle2D pieArea, PiePlotState state) {
Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
Rectangle2D labelsArea = this.simpleLabelOffset.createInsetRectangle(pieArea);
double runningTotal = 0.0;
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Comparable key = (Comparable) iterator.next();
boolean include;
double v = 0.0;
Number n = getDataset().getValue(key);
if (n == null) {
include = !getIgnoreNullValues();
} else {
v = n.doubleValue();
include = getIgnoreZeroValues() ? v > 0.0 : v >= 0.0;
}
if (include) {
runningTotal = runningTotal + v;
// work out the mid angle (0 - 90 and 270 - 360) = right,
// otherwise left
double mid = getStartAngle() + (getDirection().getFactor() * ((runningTotal - v / 2.0) * 360) / totalValue);
Arc2D arc = new Arc2D.Double(labelsArea, getStartAngle(), mid - getStartAngle(), Arc2D.OPEN);
int x = (int) arc.getEndPoint().getX();
int y = (int) arc.getEndPoint().getY();
PieSectionLabelGenerator myLabelGenerator = getLabelGenerator();
if (myLabelGenerator == null) {
continue;
}
String label = myLabelGenerator.generateSectionLabel(this.dataset, key);
if (label == null) {
continue;
}
g2.setFont(this.labelFont);
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtilities.getTextBounds(label, g2, fm);
Rectangle2D out = this.labelPadding.createOutsetRectangle(bounds);
Shape bg = ShapeUtilities.createTranslatedShape(out, x - bounds.getCenterX(), y - bounds.getCenterY());
if (this.labelShadowPaint != null && this.shadowGenerator == null) {
Shape shadow = ShapeUtilities.createTranslatedShape(bg, this.shadowXOffset, this.shadowYOffset);
g2.setPaint(this.labelShadowPaint);
g2.fill(shadow);
}
if (this.labelBackgroundPaint != null) {
g2.setPaint(this.labelBackgroundPaint);
g2.fill(bg);
}
if (this.labelOutlinePaint != null && this.labelOutlineStroke != null) {
g2.setPaint(this.labelOutlinePaint);
g2.setStroke(this.labelOutlineStroke);
g2.draw(bg);
}
g2.setPaint(this.labelPaint);
g2.setFont(this.labelFont);
TextUtilities.drawAlignedString(label, g2, x, y, TextAnchor.CENTER);
}
}
g2.setComposite(originalComposite);
}Example 15
| Project: mafscaling-master File: LogView.java View source code |
@Override
public void chartMouseMoved(ChartMouseEvent event) {
try {
wotPlot.clearRangeMarkers();
wotMarker.clearLabels(false);
Rectangle2D dataArea = wotChartPanel.getChartRenderingInfo().getPlotInfo().getDataArea();
Point2D p = wotChartPanel.translateScreenToJava2D(event.getTrigger().getPoint());
double y = 0;
double x = wotPlot.getDomainAxis(0).java2DToValue(p.getX(), dataArea, wotPlot.getDomainAxisEdge());
boolean isLeft = (p.getX() < (dataArea.getMaxX() - dataArea.getMinX()) / 2) ? true : false;
if (isLeft) {
wotMarker.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
wotMarker.setLabelTextAnchor(TextAnchor.TOP_LEFT);
} else {
wotMarker.setLabelAnchor(RectangleAnchor.TOP_LEFT);
wotMarker.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
}
XYSeriesCollection dataset;
NumberAxis rangeAxis;
boolean show = false;
for (int i = 0; i < wotPlot.getDatasetCount(); ++i) {
dataset = (XYSeriesCollection) wotPlot.getDataset(i);
if (dataset != null && dataset.getSeriesCount() > 0) {
show = true;
rangeAxis = (NumberAxis) wotPlot.getRangeAxis(i);
y = rangeAxis.java2DToValue(p.getY(), dataArea, wotPlot.getRangeAxisEdge());
wotMarker.addLabel(rangeAxis.getLabel() + ": " + df.format(y), new Color(255 - i, 255, 255), false);
}
}
if (show) {
wotMarker.setValue(x);
y = wotPlot.getRangeAxis().java2DToValue(p.getY(), dataArea, wotPlot.getRangeAxisEdge());
Marker yMarker = new ValueMarker(y);
yMarker.setPaint(Color.WHITE);
wotPlot.addRangeMarker(yMarker);
}
wotChartPanel.repaint();
} catch (Exception ex) {
ex.printStackTrace();
logger.error(ex);
}
}Example 16
| Project: opentestbed-master File: BankrollGraphUI.java View source code |
/**
* creates a JFreeChart from all the data
* @param playerToBankRoll
* @param xySeriesCollection
* @return
*/
private JFreeChart createJFreeChart(Map<String, Double> playerToBankRoll, XYSeriesCollection xySeriesCollection, int snapshotCurrentGamesPlayed) {
final JFreeChart chart = ChartFactory.createXYLineChart("Bankroll after " + (currentSeatPermutation + 1) + " seat permutation(s)", "Games", "Bankroll", xySeriesCollection, PlotOrientation.VERTICAL, true, false, false);
chart.setBackgroundPaint(Color.WHITE);
chart.getXYPlot().setBackgroundPaint(Color.WHITE);
//.get.setOutlineStroke()
XYItemRenderer xyir = chart.getXYPlot().getRenderer();
try {
xyir.setBaseStroke(new BasicStroke(3));
// bug workaround
((AbstractRenderer) xyir).setAutoPopulateSeriesStroke(false);
// xyir.setSeriesStroke(new BasicStroke(5));
// xyir.setSeriesStroke(0, ); //series line style
} catch (Exception e) {
System.err.println("Error setting style: " + e);
}
// create some Pointers to the final bankrolls
for (String playerName : playerNames) {
double finalBankroll = playerToBankRoll.get(playerName);
DecimalFormat moneyFormat = new DecimalFormat("0.00");
String resultString = playerName + ": $" + moneyFormat.format(finalBankroll) + " ($" + moneyFormat.format(finalBankroll / (snapshotCurrentGamesPlayed / 100D)) + "/100)";
final XYPointerAnnotation pointer = new XYPointerAnnotation(resultString, Math.min(snapshotCurrentGamesPlayed, numGames), finalBankroll, Math.PI * 5.9 / 6);
pointer.setBaseRadius(130.0);
pointer.setTipRadius(1.0);
pointer.setLabelOffset(10.0);
pointer.setOutlineVisible(true);
pointer.setBackgroundPaint(Color.WHITE);
chart.getXYPlot().addAnnotation(pointer);
}
// after the first permutation the next permutations get
// merges with the existing data. We show a marker, what
// data is already merged
final Marker permutationEnd = new ValueMarker(snapshotCurrentGamesPlayed % numGames);
permutationEnd.setLabel((currentSeatPermutation + 1) + " permutation(s)");
permutationEnd.setLabelAnchor(RectangleAnchor.TOP_LEFT);
permutationEnd.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
chart.getXYPlot().addDomainMarker(permutationEnd);
return chart;
}Example 17
| Project: opentrader.github.com-master File: PiePlot.java View source code |
/**
* Draws the pie section labels in the simple form.
*
* @param g2 the graphics device.
* @param keys the section keys.
* @param totalValue the total value for all sections in the pie.
* @param plotArea the plot area.
* @param pieArea the area containing the pie.
* @param state the plot state.
*
* @since 1.0.7
*/
protected void drawSimpleLabels(Graphics2D g2, List keys, double totalValue, Rectangle2D plotArea, Rectangle2D pieArea, PiePlotState state) {
Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
RectangleInsets labelInsets = new RectangleInsets(UnitType.RELATIVE, 0.18, 0.18, 0.18, 0.18);
Rectangle2D labelsArea = labelInsets.createInsetRectangle(pieArea);
double runningTotal = 0.0;
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Comparable key = (Comparable) iterator.next();
boolean include = true;
double v = 0.0;
Number n = getDataset().getValue(key);
if (n == null) {
include = !getIgnoreNullValues();
} else {
v = n.doubleValue();
include = getIgnoreZeroValues() ? v > 0.0 : v >= 0.0;
}
if (include) {
runningTotal = runningTotal + v;
// work out the mid angle (0 - 90 and 270 - 360) = right,
// otherwise left
double mid = getStartAngle() + (getDirection().getFactor() * ((runningTotal - v / 2.0) * 360) / totalValue);
Arc2D arc = new Arc2D.Double(labelsArea, getStartAngle(), mid - getStartAngle(), Arc2D.OPEN);
int x = (int) arc.getEndPoint().getX();
int y = (int) arc.getEndPoint().getY();
PieSectionLabelGenerator labelGenerator = getLabelGenerator();
if (labelGenerator == null) {
continue;
}
String label = labelGenerator.generateSectionLabel(this.dataset, key);
if (label == null) {
continue;
}
g2.setFont(this.labelFont);
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtilities.getTextBounds(label, g2, fm);
Rectangle2D out = this.labelPadding.createOutsetRectangle(bounds);
Shape bg = ShapeUtilities.createTranslatedShape(out, x - bounds.getCenterX(), y - bounds.getCenterY());
if (this.labelShadowPaint != null) {
Shape shadow = ShapeUtilities.createTranslatedShape(bg, this.shadowXOffset, this.shadowYOffset);
g2.setPaint(this.labelShadowPaint);
g2.fill(shadow);
}
if (this.labelBackgroundPaint != null) {
g2.setPaint(this.labelBackgroundPaint);
g2.fill(bg);
}
if (this.labelOutlinePaint != null && this.labelOutlineStroke != null) {
g2.setPaint(this.labelOutlinePaint);
g2.setStroke(this.labelOutlineStroke);
g2.draw(bg);
}
g2.setPaint(this.labelPaint);
g2.setFont(this.labelFont);
TextUtilities.drawAlignedString(getLabelGenerator().generateSectionLabel(getDataset(), key), g2, x, y, TextAnchor.CENTER);
}
}
g2.setComposite(originalComposite);
}Example 18
| Project: orsonpdf-master File: PDFBarChartDemo1.java View source code |
/**
* Creates a sample chart.
*
* @param dataset a dataset.
*
* @return The chart.
*/
private static JFreeChart createChart(CategoryDataset dataset) {
// create the chart...
JFreeChart chart = ChartFactory.createLineChart("Statistical Bar Chart Demo 1", "Type", "Value", dataset, PlotOrientation.VERTICAL, true, false, false);
CategoryPlot plot = (CategoryPlot) chart.getPlot();
// customise the range axis...
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
rangeAxis.setAutoRangeIncludesZero(false);
// customise the renderer...
StatisticalBarRenderer renderer = new StatisticalBarRenderer();
renderer.setDrawBarOutline(false);
renderer.setErrorIndicatorPaint(Color.black);
renderer.setIncludeBaseInRange(false);
plot.setRenderer(renderer);
// ensure the current theme is applied to the renderer just added
ChartUtilities.applyCurrentTheme(chart);
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
renderer.setBaseItemLabelsVisible(true);
renderer.setBaseItemLabelPaint(Color.yellow);
renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.INSIDE6, TextAnchor.BOTTOM_CENTER));
// set up gradient paints for series...
GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.blue, 0.0f, 0.0f, new Color(0, 0, 64));
GradientPaint gp1 = new GradientPaint(0.0f, 0.0f, Color.green, 0.0f, 0.0f, new Color(0, 64, 0));
renderer.setSeriesPaint(0, gp0);
renderer.setSeriesPaint(1, gp1);
return chart;
}Example 19
| Project: projects-master File: PiePlot.java View source code |
/**
* Draws the pie section labels in the simple form.
*
* @param g2 the graphics device.
* @param keys the section keys.
* @param totalValue the total value for all sections in the pie.
* @param plotArea the plot area.
* @param pieArea the area containing the pie.
* @param state the plot state.
*
* @since 1.0.7
*/
protected void drawSimpleLabels(Graphics2D g2, List keys, double totalValue, Rectangle2D plotArea, Rectangle2D pieArea, PiePlotState state) {
Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
Rectangle2D labelsArea = this.simpleLabelOffset.createInsetRectangle(pieArea);
double runningTotal = 0.0;
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Comparable key = (Comparable) iterator.next();
boolean include;
double v = 0.0;
Number n = getDataset().getValue(key);
if (n == null) {
include = !getIgnoreNullValues();
} else {
v = n.doubleValue();
include = getIgnoreZeroValues() ? v > 0.0 : v >= 0.0;
}
if (include) {
runningTotal = runningTotal + v;
// work out the mid angle (0 - 90 and 270 - 360) = right,
// otherwise left
double mid = getStartAngle() + (getDirection().getFactor() * ((runningTotal - v / 2.0) * 360) / totalValue);
Arc2D arc = new Arc2D.Double(labelsArea, getStartAngle(), mid - getStartAngle(), Arc2D.OPEN);
int x = (int) arc.getEndPoint().getX();
int y = (int) arc.getEndPoint().getY();
PieSectionLabelGenerator myLabelGenerator = getLabelGenerator();
if (myLabelGenerator == null) {
continue;
}
String label = myLabelGenerator.generateSectionLabel(this.dataset, key);
if (label == null) {
continue;
}
g2.setFont(this.labelFont);
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtilities.getTextBounds(label, g2, fm);
Rectangle2D out = this.labelPadding.createOutsetRectangle(bounds);
Shape bg = ShapeUtilities.createTranslatedShape(out, x - bounds.getCenterX(), y - bounds.getCenterY());
if (this.labelShadowPaint != null && this.shadowGenerator == null) {
Shape shadow = ShapeUtilities.createTranslatedShape(bg, this.shadowXOffset, this.shadowYOffset);
g2.setPaint(this.labelShadowPaint);
g2.fill(shadow);
}
if (this.labelBackgroundPaint != null) {
g2.setPaint(this.labelBackgroundPaint);
g2.fill(bg);
}
if (this.labelOutlinePaint != null && this.labelOutlineStroke != null) {
g2.setPaint(this.labelOutlinePaint);
g2.setStroke(this.labelOutlineStroke);
g2.draw(bg);
}
g2.setPaint(this.labelPaint);
g2.setFont(this.labelFont);
TextUtilities.drawAlignedString(label, g2, x, y, TextAnchor.CENTER);
}
}
g2.setComposite(originalComposite);
}Example 20
| Project: queueing-simulation-master File: PiePlot.java View source code |
/**
* Draws the pie section labels in the simple form.
*
* @param g2 the graphics device.
* @param keys the section keys.
* @param totalValue the total value for all sections in the pie.
* @param plotArea the plot area.
* @param pieArea the area containing the pie.
* @param state the plot state.
*
* @since 1.0.7
*/
protected void drawSimpleLabels(Graphics2D g2, List keys, double totalValue, Rectangle2D plotArea, Rectangle2D pieArea, PiePlotState state) {
Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
Rectangle2D labelsArea = this.simpleLabelOffset.createInsetRectangle(pieArea);
double runningTotal = 0.0;
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Comparable key = (Comparable) iterator.next();
boolean include = true;
double v = 0.0;
Number n = getDataset().getValue(key);
if (n == null) {
include = !getIgnoreNullValues();
} else {
v = n.doubleValue();
include = getIgnoreZeroValues() ? v > 0.0 : v >= 0.0;
}
if (include) {
runningTotal = runningTotal + v;
// work out the mid angle (0 - 90 and 270 - 360) = right,
// otherwise left
double mid = getStartAngle() + (getDirection().getFactor() * ((runningTotal - v / 2.0) * 360) / totalValue);
Arc2D arc = new Arc2D.Double(labelsArea, getStartAngle(), mid - getStartAngle(), Arc2D.OPEN);
int x = (int) arc.getEndPoint().getX();
int y = (int) arc.getEndPoint().getY();
PieSectionLabelGenerator labelGenerator = getLabelGenerator();
if (labelGenerator == null) {
continue;
}
String label = labelGenerator.generateSectionLabel(this.dataset, key);
if (label == null) {
continue;
}
g2.setFont(this.labelFont);
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtilities.getTextBounds(label, g2, fm);
Rectangle2D out = this.labelPadding.createOutsetRectangle(bounds);
Shape bg = ShapeUtilities.createTranslatedShape(out, x - bounds.getCenterX(), y - bounds.getCenterY());
if (this.labelShadowPaint != null && this.shadowGenerator == null) {
Shape shadow = ShapeUtilities.createTranslatedShape(bg, this.shadowXOffset, this.shadowYOffset);
g2.setPaint(this.labelShadowPaint);
g2.fill(shadow);
}
if (this.labelBackgroundPaint != null) {
g2.setPaint(this.labelBackgroundPaint);
g2.fill(bg);
}
if (this.labelOutlinePaint != null && this.labelOutlineStroke != null) {
g2.setPaint(this.labelOutlinePaint);
g2.setStroke(this.labelOutlineStroke);
g2.draw(bg);
}
g2.setPaint(this.labelPaint);
g2.setFont(this.labelFont);
TextUtilities.drawAlignedString(getLabelGenerator().generateSectionLabel(getDataset(), key), g2, x, y, TextAnchor.CENTER);
}
}
g2.setComposite(originalComposite);
}Example 21
| Project: snap-desktop-master File: CustomLogarithmicAxis.java View source code |
private void addHorizontalTicks(RectangleEdge edge, List ticks, double lowerBoundVal, String tickLabel, double tickVal) {
if (tickVal >= lowerBoundVal - SMALL_LOG_VALUE) {
//tick value not below lowest data value
TextAnchor anchor;
TextAnchor rotationAnchor;
double angle = 0.0;
if (isVerticalTickLabels()) {
anchor = TextAnchor.CENTER_RIGHT;
rotationAnchor = TextAnchor.CENTER_RIGHT;
if (edge == RectangleEdge.TOP) {
angle = Math.PI / 2.0;
} else {
angle = -Math.PI / 2.0;
}
} else {
if (edge == RectangleEdge.TOP) {
anchor = TextAnchor.BOTTOM_CENTER;
rotationAnchor = TextAnchor.BOTTOM_CENTER;
} else {
anchor = TextAnchor.TOP_CENTER;
rotationAnchor = TextAnchor.TOP_CENTER;
}
}
ticks.add(new NumberTick(new Double(tickVal), tickLabel, anchor, rotationAnchor, angle));
}
}Example 22
| Project: watchmaker-master File: JVMView.java View source code |
private JFreeChart createHeapChart(double maxMemory) {
TimeSeriesCollection dataSet = new TimeSeriesCollection();
dataSet.addSeries(memoryUsageSeries);
dataSet.addSeries(heapSizeSeries);
JFreeChart chart = ChartFactory.createXYAreaChart("JVM Heap", "Time", "Megabytes", dataSet, PlotOrientation.VERTICAL, // Legend.
true, // Tooltips.
false, false);
DateAxis timeAxis = new DateAxis("Time");
timeAxis.setLowerMargin(0);
timeAxis.setUpperMargin(0);
chart.getXYPlot().setDomainAxis(timeAxis);
chart.getXYPlot().getRangeAxis().setLowerBound(0);
// Add 10% to leave room for marker.
chart.getXYPlot().getRangeAxis().setUpperBound(maxMemory * 1.1);
// Add a horizontal marker to indicate the heap growth limit.
ValueMarker marker = new ValueMarker(maxMemory, Color.BLACK, new BasicStroke(1));
marker.setLabel("Maximum Permitted Heap Size (adjust with -Xmx)");
marker.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT);
marker.setLabelAnchor(RectangleAnchor.RIGHT);
chart.getXYPlot().addRangeMarker(marker);
chart.getXYPlot().getRenderer().setSeriesPaint(0, Color.RED);
chart.getXYPlot().getRenderer().setSeriesPaint(1, new Color(0, 128, 0, 128));
return chart;
}Example 23
| Project: ZazilDWH-master File: PiePlot.java View source code |
/**
* Draws the pie section labels in the simple form.
*
* @param g2 the graphics device.
* @param keys the section keys.
* @param totalValue the total value for all sections in the pie.
* @param plotArea the plot area.
* @param pieArea the area containing the pie.
* @param state the plot state.
*
* @since 1.0.7
*/
protected void drawSimpleLabels(Graphics2D g2, List keys, double totalValue, Rectangle2D plotArea, Rectangle2D pieArea, PiePlotState state) {
Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
Rectangle2D labelsArea = this.simpleLabelOffset.createInsetRectangle(pieArea);
double runningTotal = 0.0;
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Comparable key = (Comparable) iterator.next();
boolean include;
double v = 0.0;
Number n = getDataset().getValue(key);
if (n == null) {
include = !getIgnoreNullValues();
} else {
v = n.doubleValue();
include = getIgnoreZeroValues() ? v > 0.0 : v >= 0.0;
}
if (include) {
runningTotal = runningTotal + v;
// work out the mid angle (0 - 90 and 270 - 360) = right,
// otherwise left
double mid = getStartAngle() + (getDirection().getFactor() * ((runningTotal - v / 2.0) * 360) / totalValue);
Arc2D arc = new Arc2D.Double(labelsArea, getStartAngle(), mid - getStartAngle(), Arc2D.OPEN);
int x = (int) arc.getEndPoint().getX();
int y = (int) arc.getEndPoint().getY();
PieSectionLabelGenerator myLabelGenerator = getLabelGenerator();
if (myLabelGenerator == null) {
continue;
}
String label = myLabelGenerator.generateSectionLabel(this.dataset, key);
if (label == null) {
continue;
}
g2.setFont(this.labelFont);
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtilities.getTextBounds(label, g2, fm);
Rectangle2D out = this.labelPadding.createOutsetRectangle(bounds);
Shape bg = ShapeUtilities.createTranslatedShape(out, x - bounds.getCenterX(), y - bounds.getCenterY());
if (this.labelShadowPaint != null && this.shadowGenerator == null) {
Shape shadow = ShapeUtilities.createTranslatedShape(bg, this.shadowXOffset, this.shadowYOffset);
g2.setPaint(this.labelShadowPaint);
g2.fill(shadow);
}
if (this.labelBackgroundPaint != null) {
g2.setPaint(this.labelBackgroundPaint);
g2.fill(bg);
}
if (this.labelOutlinePaint != null && this.labelOutlineStroke != null) {
g2.setPaint(this.labelOutlinePaint);
g2.setStroke(this.labelOutlineStroke);
g2.draw(bg);
}
g2.setPaint(this.labelPaint);
g2.setFont(this.labelFont);
TextUtilities.drawAlignedString(label, g2, x, y, TextAnchor.CENTER);
}
}
g2.setComposite(originalComposite);
}Example 24
| Project: ASH-Viewer-master File: PiePlot.java View source code |
/**
* Draws the pie section labels in the simple form.
*
* @param g2 the graphics device.
* @param keys the section keys.
* @param totalValue the total value for all sections in the pie.
* @param plotArea the plot area.
* @param pieArea the area containing the pie.
* @param state the plot state.
*
* @since 1.0.7
*/
protected void drawSimpleLabels(Graphics2D g2, List keys, double totalValue, Rectangle2D plotArea, Rectangle2D pieArea, PiePlotState state) {
Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
RectangleInsets labelInsets = new RectangleInsets(UnitType.RELATIVE, 0.18, 0.18, 0.18, 0.18);
Rectangle2D labelsArea = labelInsets.createInsetRectangle(pieArea);
double runningTotal = 0.0;
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Comparable key = (Comparable) iterator.next();
boolean include = true;
double v = 0.0;
Number n = getDataset().getValue(key);
if (n == null) {
include = !getIgnoreNullValues();
} else {
v = n.doubleValue();
include = getIgnoreZeroValues() ? v > 0.0 : v >= 0.0;
}
if (include) {
runningTotal = runningTotal + v;
// work out the mid angle (0 - 90 and 270 - 360) = right,
// otherwise left
double mid = getStartAngle() + (getDirection().getFactor() * ((runningTotal - v / 2.0) * 360) / totalValue);
Arc2D arc = new Arc2D.Double(labelsArea, getStartAngle(), mid - getStartAngle(), Arc2D.OPEN);
int x = (int) arc.getEndPoint().getX();
int y = (int) arc.getEndPoint().getY();
PieSectionLabelGenerator labelGenerator = getLabelGenerator();
if (labelGenerator == null) {
continue;
}
String label = labelGenerator.generateSectionLabel(this.dataset, key);
if (label == null) {
continue;
}
g2.setFont(this.labelFont);
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtilities.getTextBounds(label, g2, fm);
Rectangle2D out = this.labelPadding.createOutsetRectangle(bounds);
Shape bg = ShapeUtilities.createTranslatedShape(out, x - bounds.getCenterX(), y - bounds.getCenterY());
if (this.labelShadowPaint != null) {
Shape shadow = ShapeUtilities.createTranslatedShape(bg, this.shadowXOffset, this.shadowYOffset);
g2.setPaint(this.labelShadowPaint);
g2.fill(shadow);
}
if (this.labelBackgroundPaint != null) {
g2.setPaint(this.labelBackgroundPaint);
g2.fill(bg);
}
if (this.labelOutlinePaint != null && this.labelOutlineStroke != null) {
g2.setPaint(this.labelOutlinePaint);
g2.setStroke(this.labelOutlineStroke);
g2.draw(bg);
}
g2.setPaint(this.labelPaint);
g2.setFont(this.labelFont);
TextUtilities.drawAlignedString(getLabelGenerator().generateSectionLabel(getDataset(), key), g2, x, y, TextAnchor.CENTER);
}
}
g2.setComposite(originalComposite);
}Example 25
| Project: atlasframework-master File: FeatureClassification.java View source code |
@Override
public BufferedImage createHistogramImage(boolean showMean, boolean showSd, int histogramBins, String label_xachsis) throws InterruptedException, IOException {
HistogramDataset hds = new HistogramDataset();
DoubleArrayList valuesAL;
valuesAL = getStatistics().elements();
// new double[] {0.4,3,4,2,5.,22.,4.,2.,33.,12.}
double[] elements = Arrays.copyOf(valuesAL.elements(), getStatistics().size());
hds.addSeries(1, elements, histogramBins);
/** Statically label the Y Axis **/
String label_yachsis = ASUtil.R("QuantitiesClassificationGUI.Histogram.YAxisLabel");
JFreeChart chart = org.jfree.chart.ChartFactory.createHistogram(null, label_xachsis, label_yachsis, hds, PlotOrientation.VERTICAL, false, true, true);
/***********************************************************************
* Paint the classes into the JFreeChart
*/
int countLimits = 0;
for (Double cLimit : getClassLimits()) {
ValueMarker marker = new ValueMarker(cLimit);
XYPlot plot = chart.getXYPlot();
marker.setPaint(Color.orange);
marker.setLabel(String.valueOf(countLimits));
marker.setLabelAnchor(RectangleAnchor.TOP_LEFT);
marker.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
plot.addDomainMarker(marker);
countLimits++;
}
/***********************************************************************
* Optionally painting SD and MEAN into the histogram
*/
try {
if (showSd) {
ValueMarker marker;
marker = new ValueMarker(getStatistics().standardDeviation(), Color.green.brighter(), new BasicStroke(1.5f));
XYPlot plot = chart.getXYPlot();
marker.setLabel(ASUtil.R("QuantitiesClassificationGUI.Histogram.SD.ShortLabel"));
marker.setLabelAnchor(RectangleAnchor.BOTTOM_LEFT);
marker.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT);
plot.addDomainMarker(marker);
}
if (showMean) {
ValueMarker marker;
marker = new ValueMarker(getStatistics().mean(), Color.green.darker(), new BasicStroke(1.5f));
XYPlot plot = chart.getXYPlot();
marker.setLabel(ASUtil.R("QuantitiesClassificationGUI.Histogram.Mean.ShortLabel"));
marker.setLabelAnchor(RectangleAnchor.BOTTOM_LEFT);
marker.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT);
plot.addDomainMarker(marker);
}
} catch (Exception e) {
LOGGER.error("Painting SD and MEAN into the histogram", e);
}
/***********************************************************************
* Render the Chart
*/
BufferedImage image = chart.createBufferedImage(400, 200);
return image;
}Example 26
| Project: cewolf-master File: AnnotationProcessor.java View source code |
public void processChart(Object chart, Map params) {
String text = "text goes here";
String fontName = "SansSerif";
int fontSize = 14;
boolean isBold = false;
boolean isItalic = false;
double x = 0.0;
double y = 0.0;
String category = null;
double value = 0.0;
TextAnchor textAnchor = TextAnnotation.DEFAULT_TEXT_ANCHOR;
Color textPaint = new Color(0, 0, 0);
Color arrowPaint = new Color(0, 0, 0);
double arrowAngle = 0;
boolean drawArrow = false;
String str = (String) params.get("text");
if (str != null && str.trim().length() > 0)
text = str.trim();
String fontNameParam = (String) params.get("fontname");
if (fontNameParam != null && fontNameParam.trim().length() > 0)
fontName = fontNameParam.trim();
String fontSizeParam = (String) params.get("fontsize");
if (fontSizeParam != null && fontSizeParam.trim().length() > 0) {
try {
fontSize = Integer.parseInt(fontSizeParam);
if (fontSize < 4)
fontSize = 14;
} catch (NumberFormatException nfex) {
}
}
String boldParam = (String) params.get("bold");
if (boldParam != null)
isBold = "true".equals(boldParam.toLowerCase());
String italicParam = (String) params.get("italic");
if (italicParam != null)
isItalic = "true".equals(italicParam.toLowerCase());
Font font = new Font(fontName, (isBold ? Font.BOLD : 0) + (isItalic ? Font.ITALIC : 0), fontSize);
str = (String) params.get("x");
if (str != null) {
try {
x = Double.parseDouble(str);
} catch (NumberFormatException nfex) {
}
}
str = (String) params.get("y");
if (str != null) {
try {
y = Double.parseDouble(str);
} catch (NumberFormatException nfex) {
}
}
str = (String) params.get("category");
if (str != null && str.trim().length() > 0)
category = str.trim();
str = (String) params.get("value");
if (str != null) {
try {
value = Double.parseDouble(str);
} catch (NumberFormatException nfex) {
}
}
str = (String) params.get("textPaint");
if (str != null && str.trim().length() > 0) {
try {
textPaint = Color.decode(str);
} catch (NumberFormatException nfex) {
}
}
str = (String) params.get("arrowPaint");
if (str != null && str.trim().length() > 0) {
try {
arrowPaint = Color.decode(str);
drawArrow = true;
} catch (NumberFormatException nfex) {
}
}
str = (String) params.get("arrowAngle");
if (str != null) {
try {
arrowAngle = Double.parseDouble(str);
drawArrow = true;
} catch (NumberFormatException nfex) {
}
}
str = (String) params.get("textAnchor");
if (str != null) {
if ("BASELINE_CENTER".equals(str))
textAnchor = TextAnchor.BASELINE_CENTER;
else if ("BASELINE_LEFT".equals(str))
textAnchor = TextAnchor.BASELINE_LEFT;
else if ("BASELINE_RIGHT".equals(str))
textAnchor = TextAnchor.BASELINE_RIGHT;
else if ("BOTTOM_CENTER".equals(str))
textAnchor = TextAnchor.BOTTOM_CENTER;
else if ("BOTTOM_LEFT".equals(str))
textAnchor = TextAnchor.BOTTOM_LEFT;
else if ("BOTTOM_RIGHT".equals(str))
textAnchor = TextAnchor.BOTTOM_RIGHT;
else if ("CENTER".equals(str))
textAnchor = TextAnchor.CENTER;
else if ("CENTER_LEFT".equals(str))
textAnchor = TextAnchor.CENTER_LEFT;
else if ("CENTER_RIGHT".equals(str))
textAnchor = TextAnchor.CENTER_RIGHT;
else if ("HALF_ASCENT_CENTER".equals(str))
textAnchor = TextAnchor.HALF_ASCENT_CENTER;
else if ("HALF_ASCENT_LEFT".equals(str))
textAnchor = TextAnchor.HALF_ASCENT_LEFT;
else if ("HALF_ASCENT_RIGHT".equals(str))
textAnchor = TextAnchor.HALF_ASCENT_RIGHT;
else if ("TOP_CENTER".equals(str))
textAnchor = TextAnchor.TOP_CENTER;
else if ("TOP_LEFT".equals(str))
textAnchor = TextAnchor.TOP_LEFT;
else if ("TOP_RIGHT".equals(str))
textAnchor = TextAnchor.TOP_RIGHT;
}
Plot plot = ((JFreeChart) chart).getPlot();
if (plot instanceof XYPlot) {
XYTextAnnotation anno = drawArrow ? new XYPointerAnnotation(text, x, y, arrowAngle) : new XYTextAnnotation(text, x, y);
anno.setPaint(textPaint);
anno.setFont(font);
anno.setTextAnchor(textAnchor);
if (drawArrow) {
((XYPointerAnnotation) anno).setArrowPaint(arrowPaint);
}
((XYPlot) plot).addAnnotation(anno);
} else if (plot instanceof CategoryPlot) {
CategoryTextAnnotation anno = drawArrow ? new CategoryPointerAnnotation(text, category, value, arrowAngle) : new CategoryTextAnnotation(text, category, value);
anno.setPaint(textPaint);
anno.setFont(font);
anno.setTextAnchor(textAnchor);
if (drawArrow) {
((CategoryPointerAnnotation) anno).setArrowPaint(arrowPaint);
}
((CategoryPlot) plot).addAnnotation(anno);
}
}Example 27
| Project: cids-custom-switchon-master File: RaineventChartPanel.java View source code |
/**
* DOCUMENT ME!
*
* @param dataset DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private JFreeChart createChart(final DefaultCategoryDataset dataset) {
final JFreeChart chart = ChartFactory.createBarChart(null, org.openide.util.NbBundle.getMessage(RaineventChartPanel.class, "RaineventChartPanel.createChart(DefaultCategoryDataset).xAxis"), org.openide.util.NbBundle.getMessage(RaineventChartPanel.class, "RaineventChartPanel.createChart(DefaultCategoryDataset).yAxis"), dataset, PlotOrientation.VERTICAL, false, false, false);
// set the background color for the chart...
chart.setBackgroundPaint(Color.white);
// get a reference to the plot for further customisation...
final CategoryPlot plot = chart.getCategoryPlot();
plot.setBackgroundPaint(Color.lightGray);
plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinePaint(Color.white);
// set the range axis to display integers only...
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
rangeAxis.setUpperMargin(0.15);
final StackedBarRenderer renderer = new StackedBarRenderer(false);
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
renderer.setBaseItemLabelsVisible(true);
renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER));
renderer.setSeriesPaint(0, ChartColor.VERY_LIGHT_BLUE);
renderer.setShadowVisible(false);
chart.getCategoryPlot().setRenderer(renderer);
return chart;
}Example 28
| Project: ITK-Stock-master File: PiePlot.java View source code |
/**
* Draws the pie section labels in the simple form.
*
* @param g2 the graphics device.
* @param keys the section keys.
* @param totalValue the total value for all sections in the pie.
* @param plotArea the plot area.
* @param pieArea the area containing the pie.
* @param state the plot state.
*
* @since 1.0.7
*/
protected void drawSimpleLabels(Graphics2D g2, List keys, double totalValue, Rectangle2D plotArea, Rectangle2D pieArea, PiePlotState state) {
Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
RectangleInsets labelInsets = new RectangleInsets(UnitType.RELATIVE, 0.18, 0.18, 0.18, 0.18);
Rectangle2D labelsArea = labelInsets.createInsetRectangle(pieArea);
double runningTotal = 0.0;
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Comparable key = (Comparable) iterator.next();
boolean include = true;
double v = 0.0;
Number n = getDataset().getValue(key);
if (n == null) {
include = !getIgnoreNullValues();
} else {
v = n.doubleValue();
include = getIgnoreZeroValues() ? v > 0.0 : v >= 0.0;
}
if (include) {
runningTotal = runningTotal + v;
// work out the mid angle (0 - 90 and 270 - 360) = right,
// otherwise left
double mid = getStartAngle() + (getDirection().getFactor() * ((runningTotal - v / 2.0) * 360) / totalValue);
Arc2D arc = new Arc2D.Double(labelsArea, getStartAngle(), mid - getStartAngle(), Arc2D.OPEN);
int x = (int) arc.getEndPoint().getX();
int y = (int) arc.getEndPoint().getY();
PieSectionLabelGenerator labelGenerator = getLabelGenerator();
if (labelGenerator == null) {
continue;
}
String label = labelGenerator.generateSectionLabel(this.dataset, key);
if (label == null) {
continue;
}
g2.setFont(this.labelFont);
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtilities.getTextBounds(label, g2, fm);
Rectangle2D out = this.labelPadding.createOutsetRectangle(bounds);
Shape bg = ShapeUtilities.createTranslatedShape(out, x - bounds.getCenterX(), y - bounds.getCenterY());
if (this.labelShadowPaint != null) {
Shape shadow = ShapeUtilities.createTranslatedShape(bg, this.shadowXOffset, this.shadowYOffset);
g2.setPaint(this.labelShadowPaint);
g2.fill(shadow);
}
if (this.labelBackgroundPaint != null) {
g2.setPaint(this.labelBackgroundPaint);
g2.fill(bg);
}
if (this.labelOutlinePaint != null && this.labelOutlineStroke != null) {
g2.setPaint(this.labelOutlinePaint);
g2.setStroke(this.labelOutlineStroke);
g2.draw(bg);
}
g2.setPaint(this.labelPaint);
g2.setFont(this.labelFont);
TextUtilities.drawAlignedString(getLabelGenerator().generateSectionLabel(getDataset(), key), g2, x, y, TextAnchor.CENTER);
}
}
g2.setComposite(originalComposite);
}Example 29
| Project: Java_gui_4_ECF-master File: PiePlot.java View source code |
/**
* Draws the pie section labels in the simple form.
*
* @param g2 the graphics device.
* @param keys the section keys.
* @param totalValue the total value for all sections in the pie.
* @param plotArea the plot area.
* @param pieArea the area containing the pie.
* @param state the plot state.
*
* @since 1.0.7
*/
protected void drawSimpleLabels(Graphics2D g2, List keys, double totalValue, Rectangle2D plotArea, Rectangle2D pieArea, PiePlotState state) {
Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
Rectangle2D labelsArea = this.simpleLabelOffset.createInsetRectangle(pieArea);
double runningTotal = 0.0;
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Comparable key = (Comparable) iterator.next();
boolean include = true;
double v = 0.0;
Number n = getDataset().getValue(key);
if (n == null) {
include = !getIgnoreNullValues();
} else {
v = n.doubleValue();
include = getIgnoreZeroValues() ? v > 0.0 : v >= 0.0;
}
if (include) {
runningTotal = runningTotal + v;
// work out the mid angle (0 - 90 and 270 - 360) = right,
// otherwise left
double mid = getStartAngle() + (getDirection().getFactor() * ((runningTotal - v / 2.0) * 360) / totalValue);
Arc2D arc = new Arc2D.Double(labelsArea, getStartAngle(), mid - getStartAngle(), Arc2D.OPEN);
int x = (int) arc.getEndPoint().getX();
int y = (int) arc.getEndPoint().getY();
PieSectionLabelGenerator labelGenerator = getLabelGenerator();
if (labelGenerator == null) {
continue;
}
String label = labelGenerator.generateSectionLabel(this.dataset, key);
if (label == null) {
continue;
}
g2.setFont(this.labelFont);
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtilities.getTextBounds(label, g2, fm);
Rectangle2D out = this.labelPadding.createOutsetRectangle(bounds);
Shape bg = ShapeUtilities.createTranslatedShape(out, x - bounds.getCenterX(), y - bounds.getCenterY());
if (this.labelShadowPaint != null && this.shadowGenerator == null) {
Shape shadow = ShapeUtilities.createTranslatedShape(bg, this.shadowXOffset, this.shadowYOffset);
g2.setPaint(this.labelShadowPaint);
g2.fill(shadow);
}
if (this.labelBackgroundPaint != null) {
g2.setPaint(this.labelBackgroundPaint);
g2.fill(bg);
}
if (this.labelOutlinePaint != null && this.labelOutlineStroke != null) {
g2.setPaint(this.labelOutlinePaint);
g2.setStroke(this.labelOutlineStroke);
g2.draw(bg);
}
g2.setPaint(this.labelPaint);
g2.setFont(this.labelFont);
TextUtilities.drawAlignedString(getLabelGenerator().generateSectionLabel(getDataset(), key), g2, x, y, TextAnchor.CENTER);
}
}
g2.setComposite(originalComposite);
}Example 30
| Project: jeql-master File: CategoryChart.java View source code |
/**
* Creates a chart.
*
* @param dataset the dataset.
*
* @return A chart.
*/
private JFreeChart createChart(CategoryDataset dataset) {
String chartType = getChartType();
JFreeChart chart = null;
if (chartType == CHART_TYPE_LINE && param.isExtruded) {
chart = ChartFactory.createLineChart3D(param.title, param.axisXTitle, param.axisYTitle, dataset, param.plotOrientation, param.showLegend, false, false);
} else if (chartType == CHART_TYPE_LINE && param.isFilled)
chart = ChartFactory.createAreaChart(param.title, param.axisXTitle, param.axisYTitle, dataset, param.plotOrientation, param.showLegend, false, false);
else if (chartType == CHART_TYPE_BAR && param.isExtruded)
chart = ChartFactory.createBarChart3D(param.title, param.axisXTitle, param.axisYTitle, dataset, param.plotOrientation, param.showLegend, false, false);
else if (chartType == CHART_TYPE_LINE) {
chart = ChartFactory.createLineChart(param.title, param.axisXTitle, param.axisYTitle, dataset, param.plotOrientation, param.showLegend, false, false);
} else if (chartType == CHART_TYPE_BAR) {
// Create a simple Bar chart
chart = ChartFactory.createBarChart(param.title, param.axisXTitle, param.axisYTitle, dataset, param.plotOrientation, param.showLegend, false, false);
} else if (chartType == CHART_TYPE_BAR_STACKED && param.isExtruded) {
chart = ChartFactory.createStackedBarChart3D(param.title, param.axisXTitle, param.axisYTitle, dataset, param.plotOrientation, param.showLegend, false, false);
} else if (chartType == CHART_TYPE_BAR_STACKED) {
chart = ChartFactory.createStackedBarChart(param.title, param.axisXTitle, param.axisYTitle, dataset, param.plotOrientation, param.showLegend, false, false);
}
CategoryPlot plot = chart.getCategoryPlot();
// set X axis label angles
if (param.axisXLabelRotation != 0.0) {
CategoryAxis axis = plot.getDomainAxis();
axis.setCategoryLabelPositions(getCategoryLabelPosition(param.axisXLabelRotation));
}
CategoryItemRenderer renderer = plot.getRenderer();
if (param.showItemLabels) {
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
renderer.setBaseItemLabelsVisible(true);
if (param.itemLabelRotation != 0.0) {
double ang = -1 * Math.PI / 2 * param.itemLabelRotation;
ItemLabelPosition pos = renderer.getBasePositiveItemLabelPosition();
ItemLabelPosition pos2 = new ItemLabelPosition(pos.getItemLabelAnchor(), TextAnchor.CENTER_LEFT, TextAnchor.CENTER_LEFT, ang);
renderer.setBasePositiveItemLabelPosition(pos2);
}
}
// set up bar painting
if (param.color != null)
renderer.setSeriesPaint(0, param.color);
if (renderer instanceof BarRenderer) {
BarRenderer barRend = (BarRenderer) renderer;
// don't draw shadow
barRend.setShadowVisible(false);
barRend.setDrawBarOutline(false);
// use flat filled bar rather than rounded bar with sheen
barRend.setBarPainter(new StandardBarPainter());
}
chart.getCategoryPlot().setRenderer(renderer);
return chart;
}Example 31
| Project: jgrasstools-master File: Scatter.java View source code |
public void addAnnotation(String text, double x) {
XYPlot plot = (XYPlot) getChart().getPlot();
Color color = new Color(0, 0, 0, 100);
Marker updateMarker = new ValueMarker(x, color, new BasicStroke(2f));
plot.addDomainMarker(updateMarker);
if (text != null) {
XYTextAnnotation updateLabel = new XYTextAnnotation(text, x, 0);
updateLabel.setRotationAnchor(TextAnchor.BASELINE_CENTER);
updateLabel.setTextAnchor(TextAnchor.BASELINE_CENTER);
updateLabel.setRotationAngle(-3.14 / 2);
updateLabel.setPaint(Color.black);
plot.addAnnotation(updateLabel);
}
setShapeLinesVisibility(plot);
}Example 32
| Project: jMemorize-master File: DeckChartPanel.java View source code |
private JFreeChart createChart() {
m_dataset = createDefaultDataSet();
JFreeChart chart = ChartFactory.createStackedBarChart3D(// chart title
null, // domain axis label
null, // range axis label //$NON-NLS-1$
Localization.get("DeckChart.CARDS"), // data
m_dataset, // the plot orientation
PlotOrientation.VERTICAL, // include legend
true, // tooltips
true, // urls
false);
// setup legend
// TODO we used to do this for the old jfreechar version, but it's not clear why.
// can we get rid of it?
LegendTitle legend = chart.getLegend();
// legend.setsetRenderingOrder(LegendRenderingOrder.REVERSE);
legend.setItemFont(legend.getItemFont().deriveFont(11f));
// setup plot
CategoryPlot plot = (CategoryPlot) chart.getPlot();
TickUnitSource tickUnits = NumberAxis.createIntegerTickUnits();
//CHECK use locale
plot.getRangeAxis().setStandardTickUnits(tickUnits);
plot.setForegroundAlpha(0.99f);
// setup renderer
m_barRenderer = new MyBarRenderer();
m_barRenderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());
m_barRenderer.setItemLabelsVisible(true);
m_barRenderer.setPositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER));
plot.setRenderer(m_barRenderer);
setSeriesPaint();
return chart;
}Example 33
| Project: jrecruiter-master File: ShowStatisticsAction.java View source code |
private static JFreeChart createChart(final CategoryDataset categorydataset, final String chartTitle) {
final JFreeChart chart = ChartFactory.createBarChart(chartTitle, "Jobs", "Number of Hits", categorydataset, PlotOrientation.VERTICAL, true, true, false);
final CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();
categoryplot.setNoDataMessage("NO DATA!");
chart.setBackgroundPaint(new Color(245, 245, 255));
chart.setBorderPaint(new Color(204, 204, 204));
chart.setBorderStroke(new BasicStroke(1f));
final LegendTitle legend = chart.getLegend();
legend.setWidth(1000);
legend.setPosition(RectangleEdge.BOTTOM);
final BlockBorder border = new BlockBorder(new Color(204, 204, 204));
legend.setBorder(border);
final CategoryPlot categoryPlot = (CategoryPlot) chart.getPlot();
categoryPlot.setBackgroundPaint(Color.WHITE);
categoryPlot.setRangeGridlinePaint(new Color(204, 204, 204));
categoryPlot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
final NumberAxis numberaxis = (NumberAxis) categoryPlot.getRangeAxis();
numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
final BarRenderer renderer = (BarRenderer) categoryPlot.getRenderer();
renderer.setDrawBarOutline(true);
final ItemLabelPosition itemlabelposition = new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER);
renderer.setPositiveItemLabelPosition(itemlabelposition);
renderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());
renderer.setItemLabelsVisible(true);
return chart;
}Example 34
| Project: KukaWii-master File: PiePlot.java View source code |
/**
* Draws the pie section labels in the simple form.
*
* @param g2 the graphics device.
* @param keys the section keys.
* @param totalValue the total value for all sections in the pie.
* @param plotArea the plot area.
* @param pieArea the area containing the pie.
* @param state the plot state.
*
* @since 1.0.7
*/
protected void drawSimpleLabels(Graphics2D g2, List keys, double totalValue, Rectangle2D plotArea, Rectangle2D pieArea, PiePlotState state) {
Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
Rectangle2D labelsArea = this.simpleLabelOffset.createInsetRectangle(pieArea);
double runningTotal = 0.0;
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Comparable key = (Comparable) iterator.next();
boolean include = true;
double v = 0.0;
Number n = getDataset().getValue(key);
if (n == null) {
include = !getIgnoreNullValues();
} else {
v = n.doubleValue();
include = getIgnoreZeroValues() ? v > 0.0 : v >= 0.0;
}
if (include) {
runningTotal = runningTotal + v;
// work out the mid angle (0 - 90 and 270 - 360) = right,
// otherwise left
double mid = getStartAngle() + (getDirection().getFactor() * ((runningTotal - v / 2.0) * 360) / totalValue);
Arc2D arc = new Arc2D.Double(labelsArea, getStartAngle(), mid - getStartAngle(), Arc2D.OPEN);
int x = (int) arc.getEndPoint().getX();
int y = (int) arc.getEndPoint().getY();
PieSectionLabelGenerator labelGenerator = getLabelGenerator();
if (labelGenerator == null) {
continue;
}
String label = labelGenerator.generateSectionLabel(this.dataset, key);
if (label == null) {
continue;
}
g2.setFont(this.labelFont);
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtilities.getTextBounds(label, g2, fm);
Rectangle2D out = this.labelPadding.createOutsetRectangle(bounds);
Shape bg = ShapeUtilities.createTranslatedShape(out, x - bounds.getCenterX(), y - bounds.getCenterY());
if (this.labelShadowPaint != null && this.shadowGenerator == null) {
Shape shadow = ShapeUtilities.createTranslatedShape(bg, this.shadowXOffset, this.shadowYOffset);
g2.setPaint(this.labelShadowPaint);
g2.fill(shadow);
}
if (this.labelBackgroundPaint != null) {
g2.setPaint(this.labelBackgroundPaint);
g2.fill(bg);
}
if (this.labelOutlinePaint != null && this.labelOutlineStroke != null) {
g2.setPaint(this.labelOutlinePaint);
g2.setStroke(this.labelOutlineStroke);
g2.draw(bg);
}
g2.setPaint(this.labelPaint);
g2.setFont(this.labelFont);
TextUtilities.drawAlignedString(getLabelGenerator().generateSectionLabel(getDataset(), key), g2, x, y, TextAnchor.CENTER);
}
}
g2.setComposite(originalComposite);
}Example 35
| Project: nmonvisualizer-master File: LineChartAnnotationDialog.java View source code |
@Override
public void actionPerformed(ActionEvent e) {
String line = lineType.getSelection().getActionCommand();
String text = annotation.getText();
if (text != null) {
text = text.trim();
}
if ("Vertical".equals(line)) {
ValueMarker marker = new DomainValueMarker(getX());
marker.setLabelOffset(new RectangleInsets(5, 5, 5, 5));
marker.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
marker.setLabel(text);
formatMarker(marker);
if (marker != null) {
xyPlot.addDomainMarker(marker);
firePropertyChange("annotation", null, marker);
}
} else if ("Horizontal".equals(line)) {
ValueMarker marker = new RangeValueMarker(getY());
marker.setLabelTextAnchor(TextAnchor.BASELINE_LEFT);
marker.setLabel(text);
formatMarker(marker);
if (marker != null) {
xyPlot.addRangeMarker(marker);
firePropertyChange("annotation", null, marker);
}
} else if ("None".equals(line)) {
if (!"".equals(text)) {
XYTextAnnotation annotation = new XYTextAnnotation(text, getX(), getY());
annotation.setFont(Styles.ANNOTATION_FONT);
annotation.setPaint(Styles.ANNOTATION_COLOR);
if (annotation != null) {
xyPlot.addAnnotation(annotation);
firePropertyChange("annotation", null, annotation);
}
}
// else no annotation needed if no text
} else {
throw new IllegalStateException("unknown annotation line type");
}
dispose();
}Example 36
| Project: ouvidoria-master File: PlotEnhancer.java View source code |
private Plot enhancePlot(CategoryPlot plot, Map params) {
String txt_meta = (String) params.get("txt_meta");
Double targetValue = txt_meta == null || txt_meta.length() < 1 ? null : new Double(txt_meta);
CategoryAxis categoryAxis = plot.getDomainAxis();
categoryAxis.setCategoryMargin(.15d);
categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
//.08dpi
rangeAxis.setUpperMargin(.45d);
rangeAxis.setLowerMargin(.02d);
rangeAxis.setLabel(!"ext".equals(params.get("indicador")) ? "%" : "2".equals(params.get("sel_indicador")) ? "Tempo" : "Total");
if (targetValue != null) {
double tv = targetValue.doubleValue();
Double factor = (Double) params.get("factor");
if (factor != null) {
tv *= factor.doubleValue();
}
if (rangeAxis.getUpperBound() < tv)
rangeAxis.setUpperBound(tv);
ValueMarker marker = new ValueMarker(tv);
marker.setLabel("Meta");
marker.setLabelFont(new Font("SansSerif", Font.ITALIC, 11));
marker.setLabelAnchor(RectangleAnchor.LEFT);
marker.setLabelTextAnchor(TextAnchor.CENTER_LEFT);
marker.setPaint(new Color(222, 222, 255, 128));
plot.addRangeMarker(marker, Layer.BACKGROUND);
}
CategoryItemRenderer renderer = plot.getRenderer();
renderer.setItemLabelFont(new Font("SansSerif", Font.BOLD, 8));
CategoryLabelGenerator clg = null;
CategoryDataset dataset = plot.getDataset();
if (dataset instanceof JDBCFlatCategoryDataset) {
JDBCFlatCategoryDataset ds = (JDBCFlatCategoryDataset) dataset;
clg = ds.getLabelGenerator();
if (clg == null) {
clg = new PercentCategoryLabelGenerator(100d / ds.getGrandTotal());
PercentCategoryLabelGenerator pclg = (PercentCategoryLabelGenerator) clg;
pclg.setPercentFormatter(NumberFormat.getNumberInstance());
pclg.getValueFormatter().setMinimumFractionDigits(2);
pclg.getValueFormatter().setMaximumFractionDigits(2);
pclg.setFormatString(" {0}% ({1})");
}
}
renderer.setLabelGenerator("true".equalsIgnoreCase((String) params.get("supressLabels")) ? null : clg);
renderer.setItemLabelsVisible(!"true".equalsIgnoreCase((String) params.get("supressLabels")));
ItemLabelPosition ilb_out = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER_LEFT, TextAnchor.CENTER_LEFT, -Math.PI / 2d);
ItemLabelPosition ilb_line = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER_LEFT, TextAnchor.CENTER_LEFT, -Math.PI / 4d);
renderer.setPositiveItemLabelPosition(ilb_out);
renderer.setNegativeItemLabelPosition(ilb_out);
if (renderer instanceof BarRenderer3D) {
plot.setForegroundAlpha(0.6f);
BarRenderer3D barRenderer3D = (BarRenderer3D) renderer;
barRenderer3D.setPositiveItemLabelPositionFallback(ilb_out);
barRenderer3D.setItemMargin(0.01d);
barRenderer3D.setMaxBarWidth(.4d);
} else if (renderer instanceof LineAndShapeRenderer) {
plot.setForegroundAlpha(0.9f);
LineAndShapeRenderer lineRenderer = (LineAndShapeRenderer) renderer;
lineRenderer.setPositiveItemLabelPosition(ilb_line);
}
setSeriesPaints(COLORS, renderer);
return plot;
}Example 37
| Project: pentaho-reporting-master File: CategoricalChartExpression.java View source code |
protected void configureChart(final JFreeChart chart) {
super.configureChart(chart);
final CategoryPlot cpl = chart.getCategoryPlot();
final CategoryItemRenderer renderer = cpl.getRenderer();
if (StringUtils.isEmpty(getTooltipFormula()) == false) {
renderer.setBaseToolTipGenerator(new FormulaCategoryTooltipGenerator(getRuntime(), getTooltipFormula()));
}
if (StringUtils.isEmpty(getUrlFormula()) == false) {
renderer.setBaseItemURLGenerator(new FormulaCategoryURLGenerator(getRuntime(), getUrlFormula()));
}
if (this.categoricalLabelFormat != null) {
final StandardCategoryItemLabelGenerator scilg;
if (categoricalLabelDecimalFormat != null) {
final DecimalFormat numFormat = new DecimalFormat(categoricalLabelDecimalFormat, new DecimalFormatSymbols(getRuntime().getResourceBundleFactory().getLocale()));
numFormat.setRoundingMode(RoundingMode.HALF_UP);
scilg = new StandardCategoryItemLabelGenerator(categoricalLabelFormat, numFormat);
} else if (categoricalLabelDateFormat != null) {
scilg = new StandardCategoryItemLabelGenerator(categoricalLabelFormat, new SimpleDateFormat(categoricalLabelDateFormat, getRuntime().getResourceBundleFactory().getLocale()));
} else {
final DecimalFormat formatter = new DecimalFormat();
formatter.setDecimalFormatSymbols(new DecimalFormatSymbols(getRuntime().getResourceBundleFactory().getLocale()));
scilg = new StandardCategoryItemLabelGenerator(categoricalLabelFormat, formatter);
}
renderer.setBaseItemLabelGenerator(scilg);
}
renderer.setBaseItemLabelsVisible(Boolean.TRUE.equals(getItemsLabelVisible()));
if (getItemLabelFont() != null) {
renderer.setBaseItemLabelFont(getItemLabelFont());
}
if (categoricalItemLabelRotation != null) {
final ItemLabelPosition orgPosItemLabelPos = renderer.getBasePositiveItemLabelPosition();
if (orgPosItemLabelPos == null) {
final ItemLabelPosition pos2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER, TextAnchor.CENTER, categoricalItemLabelRotation.doubleValue());
renderer.setBasePositiveItemLabelPosition(pos2);
} else {
final ItemLabelPosition pos2 = new ItemLabelPosition(orgPosItemLabelPos.getItemLabelAnchor(), orgPosItemLabelPos.getTextAnchor(), orgPosItemLabelPos.getRotationAnchor(), categoricalItemLabelRotation.doubleValue());
renderer.setBasePositiveItemLabelPosition(pos2);
}
final ItemLabelPosition orgNegItemLabelPos = renderer.getBaseNegativeItemLabelPosition();
if (orgNegItemLabelPos == null) {
final ItemLabelPosition pos2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER, TextAnchor.CENTER, categoricalItemLabelRotation.doubleValue());
renderer.setBaseNegativeItemLabelPosition(pos2);
} else {
final ItemLabelPosition neg2 = new ItemLabelPosition(orgNegItemLabelPos.getItemLabelAnchor(), orgNegItemLabelPos.getTextAnchor(), orgNegItemLabelPos.getRotationAnchor(), categoricalItemLabelRotation.doubleValue());
renderer.setBaseNegativeItemLabelPosition(neg2);
}
}
final Font labelFont = Font.decode(getLabelFont());
final CategoryAxis categoryAxis = cpl.getDomainAxis();
categoryAxis.setLabelFont(labelFont);
categoryAxis.setTickLabelFont(labelFont);
if (getCategoryTitleFont() != null) {
categoryAxis.setLabelFont(getCategoryTitleFont());
}
if (getCategoryTickFont() != null) {
categoryAxis.setTickLabelFont(getCategoryTickFont());
}
if (maxCategoryLabelWidthRatio != null) {
categoryAxis.setMaximumCategoryLabelWidthRatio(maxCategoryLabelWidthRatio.floatValue());
}
cpl.setDomainGridlinesVisible(showGridlines);
if (labelRotation != null) {
double angle = labelRotation.doubleValue();
CategoryLabelPosition top = createUpRotationCategoryLabelPosition(PlaneDirection.TOP, angle);
CategoryLabelPosition bottom = createUpRotationCategoryLabelPosition(PlaneDirection.BOTTOM, angle);
CategoryLabelPosition left = createUpRotationCategoryLabelPosition(PlaneDirection.LEFT, angle);
CategoryLabelPosition right = createUpRotationCategoryLabelPosition(PlaneDirection.RIGHT, angle);
CategoryLabelPositions rotationLabelPositions = new CategoryLabelPositions(top, bottom, left, right);
categoryAxis.setCategoryLabelPositions(rotationLabelPositions);
}
final String[] colors = getSeriesColor();
for (int i = 0; i < colors.length; i++) {
renderer.setSeriesPaint(i, parseColorFromString(colors[i]));
}
if (lowerMargin != null) {
categoryAxis.setLowerMargin(lowerMargin.doubleValue());
}
if (upperMargin != null) {
categoryAxis.setUpperMargin(upperMargin.doubleValue());
}
if (categoryMargin != null) {
categoryAxis.setCategoryMargin(categoryMargin.doubleValue());
}
configureRangeAxis(cpl, labelFont);
}Example 38
| Project: PerformanceRegressionTest-master File: GenerateOpsPerSecChart.java View source code |
public void generateChart() throws Exception {
if (!hasProcessed)
throw new RuntimeException("Unable to generate chart before having run #process()");
DefaultCategoryDataset dataset = generateDataset();
BarRenderer3D barRenderer = new BarRenderer3D();
barRenderer.setBaseItemLabelsVisible(true);
barRenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}", new DecimalFormat("###.#")));
barRenderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.TOP_CENTER));
barRenderer.setItemMargin(0.06);
CategoryAxis catAxis = new CategoryAxis("Bench Case");
CategoryPlot basePlot = new CategoryPlot(dataset, catAxis, new NumberAxis("Operations Per Sec"), barRenderer);
basePlot.setOrientation(PlotOrientation.VERTICAL);
basePlot.setDataset(dataset);
basePlot.getRangeAxis().setLowerBound(0);
JFreeChart chart = new JFreeChart("Performance Chart", basePlot);
Dimension dimensions = new Dimension(1600, 900);
File chartFile = new File(outputFilename);
if (performanceHasDegraded) {
chart.setBackgroundPaint(Color.RED);
}
System.out.println("Saving chart to " + chartFile.getAbsolutePath());
ChartUtilities.saveChartAsPNG(chartFile, chart, (int) dimensions.getWidth(), (int) dimensions.getHeight());
}Example 39
| Project: seqcode-master File: ScatterPlot.java View source code |
/**
* Add a dataset to the plot
* @param name String
* @param datasetMatrix 2D matrix
* @param c Color
* @param dotSize int
* @param drawAnnotations boolean
*/
public void addDataset(String name, Matrix datasetMatrix, Color c, int dotSize, boolean drawAnnotations, boolean drawConnectingLines, boolean drawDots) {
data.loadDataset(name, datasetMatrix);
this.plot.setDataset(data.getDatasetIndex(), data.getDataset(data.getDatasetIndex()));
data.editRenderer(data.getDatasetIndex(), dotSize, c, drawConnectingLines, drawDots);
this.plot.setRenderer(data.getDatasetIndex(), data.getRenderer(data.getDatasetIndex()));
if (drawAnnotations) {
List<XYTextAnnotation> annots = data.getAnnotations(data.getDatasetIndex(), 0.0, 0.0, TextAnchor.BOTTOM_RIGHT, dataLabelFontSize, Font.PLAIN, c);
for (XYTextAnnotation a : annots) plot.addAnnotation(a);
}
}Example 40
| Project: PokerbotServer-master File: BankrollGraphUI.java View source code |
/**
* creates a JFreeChart from all the data
* @param playerToBankRoll
* @param xySeriesCollection
* @return
*/
private JFreeChart createJFreeChart(Map<String, Double> playerToBankRoll, XYSeriesCollection xySeriesCollection, int snapshotCurrentGamesPlayed) {
final JFreeChart chart = ChartFactory.createXYLineChart("Bankroll after " + (currentSeatPermutation + 1) + " seat permutation(s)", "Games", "Bankroll", xySeriesCollection, PlotOrientation.VERTICAL, true, false, false);
chart.setBackgroundPaint(Color.WHITE);
chart.getXYPlot().setBackgroundPaint(Color.WHITE);
//.get.setOutlineStroke()
XYItemRenderer xyir = chart.getXYPlot().getRenderer();
try {
xyir.setBaseStroke(new BasicStroke(3));
// bug workaround
((AbstractRenderer) xyir).setAutoPopulateSeriesStroke(false);
// xyir.setSeriesStroke(new BasicStroke(5));
// xyir.setSeriesStroke(0, ); //series line style
} catch (Exception e) {
System.err.println("Error setting style: " + e);
}
// create some Pointers to the final bankrolls
for (String playerName : playerNames) {
double finalBankroll = playerToBankRoll.get(playerName);
DecimalFormat moneyFormat = new DecimalFormat("0.00");
String resultString = playerName + ": $" + moneyFormat.format(finalBankroll) + " ($" + moneyFormat.format(finalBankroll / (snapshotCurrentGamesPlayed / 100D)) + "/100)";
final XYPointerAnnotation pointer = new XYPointerAnnotation(resultString, Math.min(snapshotCurrentGamesPlayed, numGames), finalBankroll, Math.PI * 5.9 / 6);
pointer.setBaseRadius(130.0);
pointer.setTipRadius(1.0);
pointer.setLabelOffset(10.0);
pointer.setOutlineVisible(true);
pointer.setBackgroundPaint(Color.WHITE);
chart.getXYPlot().addAnnotation(pointer);
}
// after the first permutation the next permutations get
// merges with the existing data. We show a marker, what
// data is already merged
final Marker permutationEnd = new ValueMarker(snapshotCurrentGamesPlayed % numGames);
permutationEnd.setLabel((currentSeatPermutation + 1) + " permutation(s)");
permutationEnd.setLabelAnchor(RectangleAnchor.TOP_LEFT);
permutationEnd.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
chart.getXYPlot().addDomainMarker(permutationEnd);
return chart;
}Example 41
| Project: compomics-utilities-master File: VennDiagramPanel.java View source code |
// </editor-fold>//GEN-END:initComponents
/**
* Update the plot.
*/
public void updatePlot() {
plotPanel.removeAll();
tooltipToDatasetMap = new HashMap<String, String>();
DefaultXYZDataset xyzDataset = new DefaultXYZDataset();
JFreeChart chart = ChartFactory.createBubbleChart(null, "X", "Y", xyzDataset, PlotOrientation.VERTICAL, false, true, false);
XYPlot plot = chart.getXYPlot();
if (currentVennDiagramType == VennDiagramType.ONE_WAY) {
plot.getRangeAxis().setRange(0.86, 1.24);
plot.getDomainAxis().setRange(0.85, 1.25);
} else if (currentVennDiagramType == VennDiagramType.TWO_WAY) {
plot.getRangeAxis().setRange(0.86, 1.24);
plot.getDomainAxis().setRange(0.85, 1.25);
} else if (currentVennDiagramType == VennDiagramType.THREE_WAY) {
plot.getRangeAxis().setRange(0.86, 1.24);
plot.getDomainAxis().setRange(0.85, 1.25);
} else {
plot.getRangeAxis().setRange(-0.04, 0.6);
plot.getDomainAxis().setRange(-0.08, 0.7);
}
plot.getRangeAxis().setVisible(false);
plot.getDomainAxis().setVisible(false);
double radius = 0.1;
Ellipse2D ellipse = new Ellipse2D.Double(1 - radius, 1 - radius, radius + radius, radius + radius);
// @TODO: make it possible set the line color and width?
XYShapeAnnotation xyShapeAnnotation = new XYShapeAnnotation(ellipse, new BasicStroke(2f), new Color(140, 140, 140, 150), datasetAColor);
plot.addAnnotation(xyShapeAnnotation);
if (currentVennDiagramType == VennDiagramType.TWO_WAY || currentVennDiagramType == VennDiagramType.THREE_WAY) {
ellipse = new Ellipse2D.Double(1 - radius + 0.1, 1 - radius, radius + radius, radius + radius);
xyShapeAnnotation = new XYShapeAnnotation(ellipse, new BasicStroke(2f), new Color(140, 140, 140, 150), datasetBColor);
plot.addAnnotation(xyShapeAnnotation);
}
if (currentVennDiagramType == VennDiagramType.THREE_WAY) {
ellipse = new Ellipse2D.Double(1 - radius + 0.05, 1 - radius + 0.1, radius + radius, radius + radius);
xyShapeAnnotation = new XYShapeAnnotation(ellipse, new BasicStroke(2f), new Color(140, 140, 140, 150), datasetCColor);
plot.addAnnotation(xyShapeAnnotation);
}
XYTextAnnotation anotation;
if (currentVennDiagramType == VennDiagramType.ONE_WAY) {
anotation = new XYTextAnnotation("" + vennDiagramResults.get("a").size(), 1.0, 1.0);
anotation.setToolTipText(groupNames.get("a"));
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "a");
// legend
if (showLegend) {
anotation = new XYTextAnnotation(groupNames.get("a"), legendDatasetAThreeWay.getX(), legendDatasetAThreeWay.getY());
anotation.setTextAnchor(TextAnchor.BASELINE_LEFT);
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeLegend));
plot.addAnnotation(anotation);
}
} else if (currentVennDiagramType == VennDiagramType.TWO_WAY) {
anotation = new XYTextAnnotation("" + vennDiagramResults.get("a").size(), 0.96, 1.0);
anotation.setToolTipText(groupNames.get("a"));
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "a");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("b").size(), 1.14, 1.0);
anotation.setToolTipText(groupNames.get("b"));
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "b");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("ab").size(), 1.05, 1.0);
anotation.setToolTipText("<html>" + groupNames.get("a") + " ∩ " + groupNames.get("b") + "</html>");
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "ab");
// legend
if (showLegend) {
anotation = new XYTextAnnotation(groupNames.get("a"), legendDatasetAThreeWay.getX(), legendDatasetAThreeWay.getY());
anotation.setTextAnchor(TextAnchor.BASELINE_LEFT);
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeLegend));
plot.addAnnotation(anotation);
anotation = new XYTextAnnotation(groupNames.get("b"), legendDatasetBThreeWay.getX(), legendDatasetBThreeWay.getY());
anotation.setTextAnchor(TextAnchor.BASELINE_LEFT);
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeLegend));
plot.addAnnotation(anotation);
}
} else if (currentVennDiagramType == VennDiagramType.THREE_WAY) {
anotation = new XYTextAnnotation("" + vennDiagramResults.get("a").size(), 0.96, 0.97);
anotation.setToolTipText(groupNames.get("a"));
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "a");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("b").size(), 1.14, 0.97);
anotation.setToolTipText(groupNames.get("b"));
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "b");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("ab").size(), 1.05, 0.97);
anotation.setToolTipText("<html>" + groupNames.get("a") + " ∩ " + groupNames.get("b") + "</html>");
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "ab");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("c").size(), 1.05, 1.14);
anotation.setToolTipText(groupNames.get("c"));
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "c");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("ac").size(), 0.99, 1.065);
anotation.setToolTipText("<html>" + groupNames.get("a") + " ∩ " + groupNames.get("c") + "</html>");
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "ac");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("bc").size(), 1.11, 1.065);
anotation.setToolTipText("<html>" + groupNames.get("b") + " ∩ " + groupNames.get("c") + "</html>");
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "bc");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("abc").size(), 1.05, 1.036);
anotation.setToolTipText("<html>" + groupNames.get("a") + " ∩ " + groupNames.get("b") + " ∩ " + groupNames.get("c") + "</html>");
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "abc");
// legend
if (showLegend) {
anotation = new XYTextAnnotation(groupNames.get("a"), legendDatasetAThreeWay.getX(), legendDatasetAThreeWay.getY());
anotation.setTextAnchor(TextAnchor.BASELINE_LEFT);
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeLegend));
plot.addAnnotation(anotation);
anotation = new XYTextAnnotation(groupNames.get("b"), legendDatasetBThreeWay.getX(), legendDatasetBThreeWay.getY());
anotation.setTextAnchor(TextAnchor.BASELINE_LEFT);
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeLegend));
plot.addAnnotation(anotation);
anotation = new XYTextAnnotation(groupNames.get("c"), legendDatasetCThreeWay.getX(), legendDatasetCThreeWay.getY());
anotation.setTextAnchor(TextAnchor.BASELINE_LEFT);
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeLegend));
plot.addAnnotation(anotation);
}
} else if (currentVennDiagramType == VennDiagramType.FOUR_WAY) {
XYBoxAnnotation anotation2 = new XYBoxAnnotation(0, 0, 0.2, 0.5, new BasicStroke(2), Color.LIGHT_GRAY, datasetAColor);
plot.addAnnotation(anotation2);
anotation2 = new XYBoxAnnotation(0.1, 0, 0.3, 0.4, new BasicStroke(2), Color.LIGHT_GRAY, datasetBColor);
plot.addAnnotation(anotation2);
anotation2 = new XYBoxAnnotation(0, 0.1, 0.4, 0.3, new BasicStroke(2), Color.LIGHT_GRAY, datasetCColor);
plot.addAnnotation(anotation2);
anotation2 = new XYBoxAnnotation(0, 0, 0.5, 0.2, new BasicStroke(2), Color.LIGHT_GRAY, datasetDColor);
plot.addAnnotation(anotation2);
anotation = new XYTextAnnotation("" + vennDiagramResults.get("a").size(), 0.15, 0.45);
anotation.setToolTipText(groupNames.get("a"));
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "a");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("ab").size(), 0.15, 0.35);
anotation.setToolTipText("<html>" + groupNames.get("a") + " ∩ " + groupNames.get("b") + "</html>");
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "ab");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("abc").size(), 0.15, 0.25);
anotation.setToolTipText("<html>" + groupNames.get("a") + " ∩ " + groupNames.get("b") + " ∩ " + groupNames.get("c") + "</html>");
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "abc");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("abcd").size(), 0.15, 0.15);
anotation.setToolTipText("<html>" + groupNames.get("a") + " ∩ " + groupNames.get("b") + " ∩ " + groupNames.get("c") + " ∩ " + groupNames.get("d") + "</html>");
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "abcd");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("abd").size(), 0.15, 0.05);
anotation.setToolTipText("<html>" + groupNames.get("a") + " ∩ " + groupNames.get("b") + " ∩ " + groupNames.get("d") + "</html>");
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "abd");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("ac").size(), 0.05, 0.25);
anotation.setToolTipText("<html>" + groupNames.get("a") + " ∩ " + groupNames.get("c") + "</html>");
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "ac");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("acd").size(), 0.05, 0.15);
anotation.setToolTipText("<html>" + groupNames.get("a") + " ∩ " + groupNames.get("c") + " ∩ " + groupNames.get("d") + "</html>");
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "acd");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("ad").size(), 0.05, 0.05);
anotation.setToolTipText("<html>" + groupNames.get("a") + " ∩ " + groupNames.get("d") + "</html>");
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "ad");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("b").size(), 0.25, 0.35);
anotation.setToolTipText("<html>" + groupNames.get("b") + "</html>");
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "b");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("bc").size(), 0.25, 0.25);
anotation.setToolTipText("<html>" + groupNames.get("b") + " ∩ " + groupNames.get("c") + "</html>");
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "bc");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("bcd").size(), 0.25, 0.15);
anotation.setToolTipText("<html>" + groupNames.get("b") + " ∩ " + groupNames.get("c") + " ∩ " + groupNames.get("d") + "</html>");
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "bcd");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("bd").size(), 0.25, 0.05);
anotation.setToolTipText("<html>" + groupNames.get("b") + " ∩ " + groupNames.get("d") + "</html>");
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "bd");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("c").size(), 0.35, 0.25);
anotation.setToolTipText("<html>" + groupNames.get("c") + "</html>");
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "c");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("cd").size(), 0.35, 0.15);
anotation.setToolTipText("<html>" + groupNames.get("c") + " ∩ " + groupNames.get("d") + "</html>");
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "cd");
anotation = new XYTextAnnotation("" + vennDiagramResults.get("d").size(), 0.45, 0.15);
anotation.setToolTipText("<html>" + groupNames.get("d") + "</html>");
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeValues));
plot.addAnnotation(anotation);
tooltipToDatasetMap.put(anotation.getToolTipText(), "d");
// legend
if (showLegend) {
anotation = new XYTextAnnotation(groupNames.get("a"), legendDatasetAFourWay.getX(), legendDatasetAFourWay.getY());
anotation.setTextAnchor(TextAnchor.BASELINE_LEFT);
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeLegend));
plot.addAnnotation(anotation);
anotation = new XYTextAnnotation(groupNames.get("b"), legendDatasetBFourWay.getX(), legendDatasetBFourWay.getY());
anotation.setTextAnchor(TextAnchor.BASELINE_LEFT);
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeLegend));
plot.addAnnotation(anotation);
anotation = new XYTextAnnotation(groupNames.get("c"), legendDatasetCFourWay.getX(), legendDatasetCFourWay.getY());
anotation.setTextAnchor(TextAnchor.BASELINE_LEFT);
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeLegend));
plot.addAnnotation(anotation);
anotation = new XYTextAnnotation(groupNames.get("d"), legendDatasetDFourWay.getX(), legendDatasetDFourWay.getY());
anotation.setTextAnchor(TextAnchor.BASELINE_LEFT);
anotation.setFont(new Font(anotation.getFont().getFontName(), Font.BOLD, fontSizeLegend));
plot.addAnnotation(anotation);
}
}
// set up the renderer
XYBubbleRenderer renderer = new XYBubbleRenderer(XYBubbleRenderer.SCALE_ON_RANGE_AXIS);
renderer.setBaseToolTipGenerator(new StandardXYZToolTipGenerator());
plot.setRenderer(renderer);
// make all datapoints semitransparent
plot.setForegroundAlpha(0.5f);
// remove space before/after the domain axis
plot.getDomainAxis().setUpperMargin(0);
plot.getDomainAxis().setLowerMargin(0);
plot.setRangeGridlinePaint(Color.black);
// hide unwanted chart details
plot.setDomainGridlinesVisible(false);
plot.setRangeGridlinesVisible(false);
chart.getPlot().setOutlineVisible(false);
// set background color
chart.getPlot().setBackgroundPaint(Color.WHITE);
chart.setBackgroundPaint(Color.WHITE);
chartPanel = new ChartPanel(chart);
// disable the pop up menu
chartPanel.setPopupMenu(null);
chartPanel.setBackground(Color.WHITE);
// add the plot to the chart
plotPanel.add(chartPanel);
plotPanel.revalidate();
plotPanel.repaint();
// add chart mouse listener
chartPanel.addChartMouseListener(new ChartMouseListener() {
public void chartMouseClicked(ChartMouseEvent cme) {
mouseClickedInChart(cme);
}
public void chartMouseMoved(ChartMouseEvent cme) {
mouseMovedInChart(cme);
}
});
// add more chart mouse listeners
chartPanel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
super.mouseClicked(e);
}
});
}Example 42
| Project: cyclos-master File: ChartPostProcessorImpl.java View source code |
@SuppressWarnings("rawtypes")
private void setMarkers(final CategoryPlot plot, final Map params) {
final Marker[] domainMarkers = (Marker[]) params.get("domainMarkers");
// this method may be extended for range markers in future.
if (domainMarkers != null && domainMarkers.length > 0) {
for (final Marker marker : domainMarkers) {
final CategoryMarker cmarker = (CategoryMarker) marker;
cmarker.setDrawAsLine(true);
if (cmarker.getLabel() != null) {
cmarker.setLabelAnchor(RectangleAnchor.TOP_LEFT);
cmarker.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
}
plot.addDomainMarker(cmarker);
}
}
}Example 43
| Project: eurocarbdb-master File: ProfilesComparisonReportChartCanvas.java View source code |
private void createChart() {
// create dataset
theDataset = createDataset();
// create axis
CategoryAxis categoryAxis = new CategoryAxis("");
categoryAxis.setCategoryLabelPositions(org.jfree.chart.axis.CategoryLabelPositions.UP_45);
ValueAxis valueAxis = new NumberAxis("Normalized Intensities");
// create renderer
CategoryItemRenderer renderer = null;
if (theOptions.REPRESENTATION == theOptions.BARS)
renderer = new org.jfree.chart.renderer.category.BarRenderer();
else if (theOptions.REPRESENTATION == theOptions.ERRORBARS)
renderer = new org.jfree.chart.renderer.category.StatisticalBarRenderer();
else if (theOptions.REPRESENTATION == theOptions.DISTRIBUTIONS)
renderer = new org.jfree.chart.renderer.category.ScatterRenderer();
ItemLabelPosition position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER);
renderer.setBasePositiveItemLabelPosition(position1);
ItemLabelPosition position2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6, TextAnchor.TOP_CENTER);
renderer.setBaseNegativeItemLabelPosition(position2);
// create plot
thePlot = new CategoryPlot(theDataset, categoryAxis, valueAxis, renderer);
thePlot.setOrientation(org.jfree.chart.plot.PlotOrientation.VERTICAL);
// add mean values
if (theOptions.REPRESENTATION == theOptions.DISTRIBUTIONS) {
thePlot.setDataset(1, createMeansDataset());
thePlot.mapDatasetToRangeAxis(1, 0);
CategoryItemRenderer lr = new org.jfree.chart.renderer.category.LevelRenderer();
lr.setPaint(Color.black);
thePlot.setRenderer(1, lr);
}
// create chart
theChart = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, thePlot, true);
theChart.setBackgroundPaint(Color.white);
theChart.setBorderVisible(false);
}Example 44
| Project: jajuk-master File: StatView.java View source code |
/**
* Collection size bars.
*
* @return the chart
*/
private ChartPanel createCollectionSize() {
try {
final DateFormat additionFormatter = UtilString.getAdditionDateFormatter();
CategoryDataset cdata = null;
JFreeChart jfchart = null;
// number of mounts we show, mounts
int iMonthsNumber = 5;
// before are set together in 'before'
long lSizeByMonth[] = new long[iMonthsNumber + 1];
// contains size ( in Go ) for each month, first cell is before
// data
int[] iMonths = getMonths(iMonthsNumber);
ReadOnlyIterator<Track> tracks = TrackManager.getInstance().getTracksIterator();
while (tracks.hasNext()) {
Track track = tracks.next();
int i = Integer.parseInt(additionFormatter.format(track.getDiscoveryDate())) / 100;
for (int j = 0; j < iMonthsNumber + 1; j++) {
if (i <= iMonths[j]) {
lSizeByMonth[j] += track.getTotalSize();
}
}
}
double[][] data = new double[1][iMonthsNumber + 1];
for (int i = 0; i < iMonthsNumber + 1; i++) {
data[0][i] = (double) lSizeByMonth[i] / 1073741824;
}
cdata = DatasetUtilities.createCategoryDataset(new String[] { "" }, getMonthsLabels(iMonthsNumber), data);
// chart, use local copy of method to use better format string for
// tooltips
jfchart = createBarChart3D(// chart
Messages.getString("StatView.7"), // domain axis label
Messages.getString("StatView.8"), // range axis label
Messages.getString("StatView.9"), // data
cdata, // orientation
PlotOrientation.VERTICAL, // include legend
false, // tooltips
true, // urls
false, "{1} = {2} GB");
CategoryPlot plot = jfchart.getCategoryPlot();
CategoryAxis axis = plot.getDomainAxis();
new CategoryLabelPosition(RectangleAnchor.TOP, TextBlockAnchor.TOP_RIGHT, TextAnchor.TOP_RIGHT, -Math.PI / 8.0, CategoryLabelWidthType.CATEGORY, 0);
axis.setCategoryLabelPositions(CategoryLabelPositions.STANDARD);
// set the background color for the chart...
plot.setNoDataMessage(Messages.getString("StatView.10"));
plot.setForegroundAlpha(0.5f);
plot.setBackgroundAlpha(0.5f);
// plot.setBackgroundImage(IconLoader.IMAGES_STAT_PAPER).getImage());
return new ChartPanel(jfchart);
} catch (Exception e) {
Log.error(e);
return null;
}
}Example 45
| Project: novelang-master File: Grapher.java View source code |
private static void addAnnotations(final XYPlot plot, final MeasurementBundle<TimeMeasurement> measurementBundle) {
final int measurementCount = measurementBundle.getMeasurementCount();
final String annotationText;
annotationText = calculateTerminationText(measurementBundle.getTermination());
if (annotationText != null && measurementCount > 0) {
final TimeMeasurement measurement = measurementBundle.getMeasurement(measurementCount - 1);
if (measurement != null) {
final XYTextAnnotation annotation = new XYTextAnnotation(annotationText, (double) measurementCount, convertToYValue(measurement));
annotation.setTextAnchor(TextAnchor.BOTTOM_RIGHT);
plot.addAnnotation(annotation);
}
}
}Example 46
| Project: openrocket-master File: SimulationPlot.java View source code |
@Override
public void drawDomainMarker(Graphics2D g2, XYPlot plot, ValueAxis domainAxis, Marker marker, Rectangle2D dataArea) {
if (!(marker instanceof ValueMarker)) {
// Use parent for all others
super.drawDomainMarker(g2, plot, domainAxis, marker, dataArea);
return;
}
/*
* Draw the normal marker, but with rotated text.
* Copied from the overridden method.
*/
ValueMarker vm = (ValueMarker) marker;
double value = vm.getValue();
Range range = domainAxis.getRange();
if (!range.contains(value)) {
return;
}
double v = domainAxis.valueToJava2D(value, dataArea, plot.getDomainAxisEdge());
PlotOrientation orientation = plot.getOrientation();
Line2D line = null;
if (orientation == PlotOrientation.HORIZONTAL) {
line = new Line2D.Double(dataArea.getMinX(), v, dataArea.getMaxX(), v);
} else {
line = new Line2D.Double(v, dataArea.getMinY(), v, dataArea.getMaxY());
}
final Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, marker.getAlpha()));
g2.setPaint(marker.getPaint());
g2.setStroke(marker.getStroke());
g2.draw(line);
String label = marker.getLabel();
RectangleAnchor anchor = marker.getLabelAnchor();
if (label != null) {
Font labelFont = marker.getLabelFont();
g2.setFont(labelFont);
g2.setPaint(marker.getLabelPaint());
Point2D coordinates = calculateDomainMarkerTextAnchorPoint(g2, orientation, dataArea, line.getBounds2D(), marker.getLabelOffset(), LengthAdjustmentType.EXPAND, anchor);
// Changed:
TextAnchor textAnchor = TextAnchor.TOP_RIGHT;
TextUtilities.drawRotatedString(label, g2, (float) coordinates.getX() + 2, (float) coordinates.getY(), textAnchor, -Math.PI / 2, textAnchor);
}
g2.setComposite(originalComposite);
}Example 47
| Project: toobs-master File: ChartUtil.java View source code |
public static void configureDomainItemLabels(BasePlot plot, AbstractRenderer renderer, Map params, boolean is3D) {
if (plot.getShowDomainItemLabels()) {
String orientation = ParameterUtil.resolveParam(plot.getOrientation(), params, "horizontal")[0];
if (orientation.equals("horizontal")) {
ItemLabelPosition position1;
if (is3D) {
position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE2, TextAnchor.CENTER_LEFT);
renderer.setItemLabelAnchorOffset(15.0d);
} else {
position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE3, TextAnchor.CENTER_LEFT);
}
renderer.setPositiveItemLabelPosition(position1);
ItemLabelPosition position2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE9, TextAnchor.CENTER_RIGHT);
renderer.setNegativeItemLabelPosition(position2);
} else if (orientation.equals("vertical")) {
ItemLabelPosition position1;
if (is3D) {
position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE1, TextAnchor.BOTTOM_CENTER);
renderer.setItemLabelAnchorOffset(10.0d);
} else {
position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER);
}
renderer.setPositiveItemLabelPosition(position1);
ItemLabelPosition position2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6, TextAnchor.TOP_CENTER);
renderer.setNegativeItemLabelPosition(position2);
}
renderer.setBaseItemLabelsVisible(true);
((CategoryItemRenderer) renderer).setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
}
}Example 48
| Project: ewcms-master File: ChartFactory.java View source code |
public byte[] export(ChartReport report, Map<String, String> pageParams) throws Exception {
if (report == null) {
return null;
}
DefaultCategoryDataset dataset = buildDataset(report, pageParams);
java.awt.Font titleFont = new java.awt.Font(report.getFontName(), report.getFontStyle(), report.getFontSize());
String chartTitle = report.getChartTitle();
chartTitle = replaceParam(pageParams, report.getParameters(), chartTitle, false);
String horizAxisLabel = report.getHorizAxisLabel();
horizAxisLabel = replaceParam(pageParams, report.getParameters(), horizAxisLabel, false);
String vertAxisLabel = report.getVertAxisLabel();
vertAxisLabel = replaceParam(pageParams, report.getParameters(), vertAxisLabel, false);
Boolean showLegend = report.getShowLegend();
Boolean showTooltips = report.getShowTooltips();
Boolean drillThroughEnabled = false;
ChartReport.Type chartType = report.getType();
CategoryURLGenerator urlGenerator = null;
JFreeChart chart = null;
switch(chartType) {
case VERTBAR:
chart = ChartGenerationService.createBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
break;
case VERTBAR3D:
chart = ChartGenerationService.createBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
break;
case HORIZBAR:
chart = ChartGenerationService.createBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
break;
case HORIZBAR3D:
chart = ChartGenerationService.createBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
break;
case STACKEDVERTBAR:
chart = ChartGenerationService.createStackedBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
break;
case STACKEDVERTBAR3D:
chart = ChartGenerationService.createStackedBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
break;
case STACKEDHORIZBAR:
chart = ChartGenerationService.createStackedBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
break;
case STACKEDHORIZBAR3D:
chart = ChartGenerationService.createStackedBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
break;
case VERTLINE:
chart = ChartGenerationService.createLineChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
break;
case HORIZLINE:
chart = ChartGenerationService.createLineChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
break;
case VERTAREA:
chart = ChartGenerationService.createAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
break;
case HORIZAREA:
chart = ChartGenerationService.createAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
break;
case VERTSTACKEDAREA:
chart = ChartGenerationService.createStackedAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
break;
case HORIZSTACKEDAREA:
chart = ChartGenerationService.createStackedAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
break;
case PIEBYCOLUMN:
chart = ChartGenerationService.createPieChart(chartTitle, titleFont, dataset, TableOrder.BY_COLUMN, showLegend, showTooltips, drillThroughEnabled, null);
break;
case PIEBYROW:
chart = ChartGenerationService.createPieChart(chartTitle, titleFont, dataset, TableOrder.BY_ROW, showLegend, showTooltips, drillThroughEnabled, null);
break;
case PIEBYCOLUMN3D:
chart = ChartGenerationService.create3DPieChart(chartTitle, titleFont, dataset, TableOrder.BY_COLUMN, showLegend, showTooltips, drillThroughEnabled, null);
break;
case PIEBYROW3D:
chart = ChartGenerationService.create3DPieChart(chartTitle, titleFont, dataset, TableOrder.BY_ROW, showLegend, showTooltips, drillThroughEnabled, null);
break;
default:
throw new BaseException("一个未定义的图表类型", "一个未定义的图表类型");
}
try {
Integer bgColorR = report.getBgColorR();
Integer bgColorG = report.getBgColorG();
Integer bgColorB = report.getBgColorB();
chart.setBackgroundPaint(new java.awt.Color(bgColorR, bgColorG, bgColorB));
String axisFontName = report.getAxisFontName();
Integer axisFontStyle = report.getAxisFontStyle();
Integer axisFontSize = report.getAxisFontSize();
java.awt.Font axisFont = new java.awt.Font(axisFontName, axisFontStyle, axisFontSize);
String axisTickFontName = report.getAxisTickFontName();
Integer axisTickFontStyle = report.getAxisTickFontStyle();
Integer axisTickFontSize = report.getAxisTickFontSize();
java.awt.Font axisTickFont = new java.awt.Font(axisTickFontName, axisTickFontStyle, axisTickFontSize);
String legendFontName = report.getLegendFontName();
Integer legendFontStyle = report.getLegendFontStyle();
Integer legendFontSize = report.getLegendFontSize();
java.awt.Font legendFont = new java.awt.Font(legendFontName, legendFontStyle, legendFontSize);
Integer tickLabelRotate = report.getTickLabelRotate();
String dataFontName = report.getDataFontName();
Integer dataFontStyle = report.getDataFontStyle();
Integer dataFontSize = report.getDataFontSize();
java.awt.Font dataFont = new java.awt.Font(dataFontName, dataFontStyle, dataFontSize);
Plot plot = chart.getPlot();
if (!(plot instanceof MultiplePiePlot)) {
CategoryPlot categoryPlot = chart.getCategoryPlot();
CategoryItemRenderer renderer = categoryPlot.getRenderer();
renderer.setBaseItemLabelGenerator(new LabelGenerator(0.0));
renderer.setBaseItemLabelFont(dataFont);
renderer.setBaseItemLabelsVisible(true);
if (chartType == ChartReport.Type.VERTLINE || chartType == ChartReport.Type.HORIZLINE) {
LineAndShapeRenderer lineRenderer = (LineAndShapeRenderer) categoryPlot.getRenderer();
lineRenderer.setBaseShapesVisible(true);
lineRenderer.setDrawOutlines(true);
lineRenderer.setUseFillPaint(true);
}
}
if (plot instanceof CategoryPlot) {
CategoryPlot catPlot = (CategoryPlot) plot;
catPlot.getDomainAxis().setLabelFont(axisFont);
catPlot.getRangeAxis().setLabelFont(axisFont);
catPlot.getDomainAxis().setTickLabelFont(axisTickFont);
catPlot.getRangeAxis().setTickLabelFont(axisTickFont);
catPlot.getDomainAxis().setMaximumCategoryLabelWidthRatio(100.0f);
double angle = -2.0 * Math.PI / 360.0 * (double) tickLabelRotate;
CategoryLabelPositions oldp = catPlot.getDomainAxis().getCategoryLabelPositions();
CategoryLabelPositions newp = new CategoryLabelPositions(oldp.getLabelPosition(RectangleEdge.TOP), new CategoryLabelPosition(RectangleAnchor.TOP, TextBlockAnchor.TOP_RIGHT, TextAnchor.TOP_RIGHT, angle, CategoryLabelWidthType.RANGE, 0.0f), oldp.getLabelPosition(RectangleEdge.LEFT), oldp.getLabelPosition(RectangleEdge.RIGHT));
catPlot.getDomainAxis().setCategoryLabelPositions(newp);
} else if (plot instanceof PiePlot3D) {
PiePlot3D piePlot = (PiePlot3D) plot;
piePlot.setLabelFont(axisFont);
piePlot.setDirection(org.jfree.util.Rotation.CLOCKWISE);
piePlot.setForegroundAlpha(0.5f);
piePlot.setNoDataMessage("æ— æ•°æ?®æ˜¾ç¤º");
} else if (plot instanceof PiePlot) {
PiePlot piePlot = (PiePlot) plot;
piePlot.setLabelFont(axisFont);
}
LegendTitle legend = (LegendTitle) chart.getLegend();
if (legend != null) {
legend.setItemFont(legendFont);
RectangleEdge legendRectEdge = RectangleEdge.BOTTOM;
Integer legendPosition = report.getLegendPosition();
switch(legendPosition) {
case 0:
legendRectEdge = RectangleEdge.LEFT;
break;
case 1:
legendRectEdge = RectangleEdge.TOP;
break;
case 2:
legendRectEdge = RectangleEdge.RIGHT;
break;
case 3:
legendRectEdge = RectangleEdge.BOTTOM;
break;
}
legend.setPosition(legendRectEdge);
}
} catch (Exception e) {
logger.error("Chart Export Exception", e);
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ChartUtilities.writeChartAsPNG(out, chart, report.getChartWidth(), report.getChartHeight());
return out.toByteArray();
}Example 49
| Project: ice-master File: BasicWeeklyCostEmailService.java View source code |
private File createImage(ApplicationGroup appgroup) throws IOException {
Map<String, Double> costs = Maps.newHashMap();
DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0);
Interval interval = new Interval(end.minusWeeks(numWeeks), end);
for (Product product : products) {
List<ResourceGroup> resourceGroups = getResourceGroups(appgroup, product);
if (resourceGroups.size() == 0) {
continue;
}
DataManager dataManager = config.managers.getCostManager(product, ConsolidateType.weekly);
if (dataManager == null) {
continue;
}
TagLists tagLists = new TagLists(accounts, regions, null, Lists.newArrayList(product), null, null, resourceGroups);
Map<Tag, double[]> data = dataManager.getData(interval, tagLists, TagType.Product, AggregateType.none, false);
for (Tag tag : data.keySet()) {
for (int week = 0; week < numWeeks; week++) {
String key = tag + "|" + week;
if (costs.containsKey(key))
costs.put(key, data.get(tag)[week] + costs.get(key));
else
costs.put(key, data.get(tag)[week]);
}
}
}
boolean hasData = false;
for (Map.Entry<String, Double> entry : costs.entrySet()) {
if (!entry.getKey().contains("monitor") && entry.getValue() != null && entry.getValue() >= 0.1) {
hasData = true;
break;
}
}
if (!hasData)
return null;
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for (Product product : products) {
for (int week = 0; week < numWeeks; week++) {
String weekStr = String.format("%s - %s week", formatter.print(end.minusWeeks(numWeeks - week)).substring(5), formatter.print(end.minusWeeks(numWeeks - week - 1)).substring(5));
dataset.addValue(costs.get(product + "|" + week), product.name, weekStr);
}
}
JFreeChart chart = ChartFactory.createBarChart3D(appgroup.getDisplayName() + " Weekly AWS Costs", "", "Costs", dataset, PlotOrientation.VERTICAL, true, false, false);
CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();
BarRenderer3D renderer = (BarRenderer3D) categoryplot.getRenderer();
renderer.setItemLabelAnchorOffset(10.0);
TextTitle title = chart.getTitle();
title.setFont(title.getFont().deriveFont((title.getFont().getSize() - 3)));
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator() {
public java.lang.String generateLabel(org.jfree.data.category.CategoryDataset dataset, int row, int column) {
return costFormatter.format(dataset.getValue(row, column));
}
});
renderer.setBaseItemLabelsVisible(true);
renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));
NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();
numberaxis.setNumberFormatOverride(costFormatter);
BufferedImage image = chart.createBufferedImage(1200, 400);
File outputfile = File.createTempFile("awscost", "png");
ImageIO.write(image, "png", outputfile);
return outputfile;
}Example 50
| Project: JadexPlayer-master File: ChartCanvas.java View source code |
/**
* An option for the barchart to display labels, even if they dont fit in
* the bar.
*
* @param forceLabels <code>true</code> if labels are forced to
* bedisplayed regardless of their size.
*/
public void setForceLabels(boolean forceLabels) {
this.forceLabels = forceLabels;
// sanity check
if (chartType == CHARTTYPE_PIECHART) {
return;
}
BarRenderer renderer = (BarRenderer) chart.getCategoryPlot().getRenderer();
if (forceLabels) {
ItemLabelPosition itemlabelposition = new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, 0.0D);
renderer.setPositiveItemLabelPositionFallback(itemlabelposition);
renderer.setNegativeItemLabelPositionFallback(itemlabelposition);
} else {
renderer.setNegativeItemLabelPositionFallback(null);
renderer.setPositiveItemLabelPositionFallback(null);
}
}Example 51
| Project: rapidminer-5-master File: ParetoChartPlotter.java View source code |
public void paintParetoChart(Graphics graphics) {
prepareData();
JFreeChart chart = createChart();
if (chart != null) {
// set the background color for the chart...
chart.setBackgroundPaint(Color.white);
chart.getPlot().setBackgroundPaint(Color.WHITE);
// bar renderer --> own 3D effect
CategoryPlot plot = chart.getCategoryPlot();
BarRenderer renderer = (BarRenderer) plot.getRenderer();
// renderer.setBarPainter(new StandardBarPainter());
renderer.setBarPainter(new RapidBarPainter());
renderer.setSeriesPaint(0, getColorProvider().getPointColor(1));
// labels on top of bars
Map<String, String> barItemLabels = new HashMap<String, String>();
Map<String, String> cumulativeItemLabels = new HashMap<String, String>();
int groupSum = 0;
int totalSum = 0;
for (Object key : totalData.getKeys()) {
String k = (String) key;
try {
Number groupValue = data.getValue(k);
Number totalValue = totalData.getValue(k);
groupSum += groupValue.intValue();
totalSum += totalValue.intValue();
barItemLabels.put(k, Tools.formatIntegerIfPossible(groupValue.doubleValue()) + " / " + Tools.formatIntegerIfPossible(totalValue.doubleValue()));
cumulativeItemLabels.put(k, groupSum + " / " + totalSum);
} catch (UnknownKeyException e) {
}
}
renderer.setSeriesItemLabelFont(0, LABEL_FONT);
if (showBarLabelsFlag) {
renderer.setSeriesItemLabelsVisible(0, true);
renderer.setSeriesItemLabelGenerator(0, new ParetoChartItemLabelGenerator(barItemLabels));
if (isLabelRotating()) {
renderer.setSeriesPositiveItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER_LEFT, TextAnchor.CENTER_LEFT, -Math.PI / 2.0d));
renderer.setSeriesNegativeItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER_LEFT, TextAnchor.CENTER_LEFT, -Math.PI / 2.0d));
}
}
LineAndShapeRenderer renderer2 = (LineAndShapeRenderer) chart.getCategoryPlot().getRenderer(1);
renderer2.setSeriesItemLabelFont(0, LABEL_FONT);
renderer2.setSeriesItemLabelPaint(0, SwingTools.VERY_DARK_BLUE.darker());
if (isLabelRotating()) {
renderer2.setSeriesPositiveItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6, TextAnchor.CENTER_RIGHT, TextAnchor.CENTER_RIGHT, -Math.PI / 2.0d));
renderer2.setSeriesNegativeItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6, TextAnchor.CENTER_RIGHT, TextAnchor.CENTER_RIGHT, -Math.PI / 2.0d));
} else {
renderer2.setSeriesPositiveItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.OUTSIDE10, TextAnchor.BOTTOM_RIGHT));
renderer2.setSeriesNegativeItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.OUTSIDE10, TextAnchor.BOTTOM_RIGHT));
}
if (showCumulativeLabelsFlag) {
renderer2.setSeriesItemLabelsVisible(0, true);
renderer2.setSeriesItemLabelGenerator(0, new ParetoChartItemLabelGenerator(cumulativeItemLabels));
}
// draw outlines
renderer.setDrawBarOutline(true);
// gridline colors
plot.setRangeGridlinePaint(Color.LIGHT_GRAY);
// legend settings
LegendTitle legend = chart.getLegend();
if (legend != null) {
legend.setPosition(RectangleEdge.TOP);
legend.setFrame(BlockBorder.NONE);
legend.setHorizontalAlignment(HorizontalAlignment.LEFT);
legend.setItemFont(LABEL_FONT);
}
Rectangle2D drawRect = new Rectangle2D.Double(0, 0, getWidth(), getHeight());
chart.draw((Graphics2D) graphics, drawRect);
}
}Example 52
| Project: rapidminer-studio-master File: ParetoChartPlotter.java View source code |
public void paintParetoChart(Graphics graphics) {
prepareData();
JFreeChart chart = createChart();
if (chart != null) {
// set the background color for the chart...
chart.setBackgroundPaint(Color.white);
chart.getPlot().setBackgroundPaint(Color.WHITE);
// bar renderer --> own 3D effect
CategoryPlot plot = chart.getCategoryPlot();
BarRenderer renderer = (BarRenderer) plot.getRenderer();
// renderer.setBarPainter(new StandardBarPainter());
renderer.setBarPainter(new RapidBarPainter());
renderer.setSeriesPaint(0, getColorProvider(true).getPointColor(1));
// labels on top of bars
Map<String, String> barItemLabels = new HashMap<>();
Map<String, String> cumulativeItemLabels = new HashMap<>();
int groupSum = 0;
int totalSum = 0;
for (Object key : totalData.getKeys()) {
String k = (String) key;
try {
Number groupValue = data.getValue(k);
Number totalValue = totalData.getValue(k);
groupSum += groupValue.intValue();
totalSum += totalValue.intValue();
barItemLabels.put(k, Tools.formatIntegerIfPossible(groupValue.doubleValue()) + " / " + Tools.formatIntegerIfPossible(totalValue.doubleValue()));
cumulativeItemLabels.put(k, groupSum + " / " + totalSum);
} catch (UnknownKeyException e) {
}
}
renderer.setSeriesItemLabelFont(0, LABEL_FONT);
if (showBarLabelsFlag) {
renderer.setSeriesItemLabelsVisible(0, true);
renderer.setSeriesItemLabelGenerator(0, new ParetoChartItemLabelGenerator(barItemLabels));
if (isLabelRotating()) {
renderer.setSeriesPositiveItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER_LEFT, TextAnchor.CENTER_LEFT, -Math.PI / 2.0d));
renderer.setSeriesNegativeItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER_LEFT, TextAnchor.CENTER_LEFT, -Math.PI / 2.0d));
}
}
LineAndShapeRenderer renderer2 = (LineAndShapeRenderer) chart.getCategoryPlot().getRenderer(1);
renderer2.setSeriesPaint(0, Color.GRAY.darker().darker());
renderer2.setSeriesItemLabelFont(0, LABEL_FONT);
renderer2.setSeriesItemLabelPaint(0, Color.BLACK);
if (isLabelRotating()) {
renderer2.setSeriesPositiveItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6, TextAnchor.CENTER_RIGHT, TextAnchor.CENTER_RIGHT, -Math.PI / 2.0d));
renderer2.setSeriesNegativeItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6, TextAnchor.CENTER_RIGHT, TextAnchor.CENTER_RIGHT, -Math.PI / 2.0d));
} else {
renderer2.setSeriesPositiveItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.OUTSIDE10, TextAnchor.BOTTOM_RIGHT));
renderer2.setSeriesNegativeItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.OUTSIDE10, TextAnchor.BOTTOM_RIGHT));
}
if (showCumulativeLabelsFlag) {
renderer2.setSeriesItemLabelsVisible(0, true);
renderer2.setSeriesItemLabelGenerator(0, new ParetoChartItemLabelGenerator(cumulativeItemLabels));
}
// draw outlines
renderer.setDrawBarOutline(true);
// gridline colors
plot.setRangeGridlinePaint(Color.BLACK);
// legend settings
LegendTitle legend = chart.getLegend();
if (legend != null) {
legend.setPosition(RectangleEdge.TOP);
legend.setFrame(BlockBorder.NONE);
legend.setHorizontalAlignment(HorizontalAlignment.LEFT);
legend.setItemFont(LABEL_FONT);
}
Rectangle2D drawRect = new Rectangle2D.Double(0, 0, getWidth(), getHeight());
chart.draw((Graphics2D) graphics, drawRect);
}
}Example 53
| Project: rapidminer-vega-master File: ParetoChartPlotter.java View source code |
public void paintParetoChart(Graphics graphics) {
prepareData();
JFreeChart chart = createChart();
if (chart != null) {
// set the background color for the chart...
chart.setBackgroundPaint(Color.white);
chart.getPlot().setBackgroundPaint(Color.WHITE);
// bar renderer --> own 3D effect
CategoryPlot plot = chart.getCategoryPlot();
BarRenderer renderer = (BarRenderer) plot.getRenderer();
// renderer.setBarPainter(new StandardBarPainter());
renderer.setBarPainter(new RapidBarPainter());
renderer.setSeriesPaint(0, getColorProvider().getPointColor(1));
// labels on top of bars
Map<String, String> barItemLabels = new HashMap<String, String>();
Map<String, String> cumulativeItemLabels = new HashMap<String, String>();
int groupSum = 0;
int totalSum = 0;
for (Object key : totalData.getKeys()) {
String k = (String) key;
try {
Number groupValue = data.getValue(k);
Number totalValue = totalData.getValue(k);
groupSum += groupValue.intValue();
totalSum += totalValue.intValue();
barItemLabels.put(k, Tools.formatIntegerIfPossible(groupValue.doubleValue()) + " / " + Tools.formatIntegerIfPossible(totalValue.doubleValue()));
cumulativeItemLabels.put(k, groupSum + " / " + totalSum);
} catch (UnknownKeyException e) {
}
}
renderer.setSeriesItemLabelFont(0, LABEL_FONT);
if (showBarLabelsFlag) {
renderer.setSeriesItemLabelsVisible(0, true);
renderer.setSeriesItemLabelGenerator(0, new ParetoChartItemLabelGenerator(barItemLabels));
if (isLabelRotating()) {
renderer.setSeriesPositiveItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER_LEFT, TextAnchor.CENTER_LEFT, -Math.PI / 2.0d));
renderer.setSeriesNegativeItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER_LEFT, TextAnchor.CENTER_LEFT, -Math.PI / 2.0d));
}
}
LineAndShapeRenderer renderer2 = (LineAndShapeRenderer) chart.getCategoryPlot().getRenderer(1);
renderer2.setSeriesItemLabelFont(0, LABEL_FONT);
renderer2.setSeriesItemLabelPaint(0, SwingTools.VERY_DARK_BLUE.darker());
if (isLabelRotating()) {
renderer2.setSeriesPositiveItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6, TextAnchor.CENTER_RIGHT, TextAnchor.CENTER_RIGHT, -Math.PI / 2.0d));
renderer2.setSeriesNegativeItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6, TextAnchor.CENTER_RIGHT, TextAnchor.CENTER_RIGHT, -Math.PI / 2.0d));
} else {
renderer2.setSeriesPositiveItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.OUTSIDE10, TextAnchor.BOTTOM_RIGHT));
renderer2.setSeriesNegativeItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.OUTSIDE10, TextAnchor.BOTTOM_RIGHT));
}
if (showCumulativeLabelsFlag) {
renderer2.setSeriesItemLabelsVisible(0, true);
renderer2.setSeriesItemLabelGenerator(0, new ParetoChartItemLabelGenerator(cumulativeItemLabels));
}
// draw outlines
renderer.setDrawBarOutline(true);
// gridline colors
plot.setRangeGridlinePaint(Color.LIGHT_GRAY);
// legend settings
LegendTitle legend = chart.getLegend();
if (legend != null) {
legend.setPosition(RectangleEdge.TOP);
legend.setFrame(BlockBorder.NONE);
legend.setHorizontalAlignment(HorizontalAlignment.LEFT);
legend.setItemFont(LABEL_FONT);
}
Rectangle2D drawRect = new Rectangle2D.Double(0, 0, getWidth(), getHeight());
chart.draw((Graphics2D) graphics, drawRect);
}
}Example 54
| Project: RomRaider-master File: DynoChartPanel.java View source code |
public void interpolate(double[] results, String[] resultStrings) {
hpAxis.setAutoRange(true);
tqAxis.setAutoRange(true);
double rangeMin = Math.min(tqAxis.getLowerBound(), hpAxis.getLowerBound());
double yMin = Math.round(rangeMin);
double ySpace = (hpAxis.getUpperBound() - hpAxis.getLowerBound()) / 25;
double xMin = ((plot.getDomainAxis().getUpperBound() - plot.getDomainAxis().getLowerBound()) / 7) + plot.getDomainAxis().getLowerBound();
hpAxis.setRange(Math.round(rangeMin), Math.round(hpAxis.getUpperBound() + ySpace));
tqAxis.setRange(Math.round(rangeMin), Math.round(tqAxis.getUpperBound() + ySpace));
bestHp = new XYDrawableAnnotation(results[1], results[0], 10, 10, cd);
hpPointer.setX(results[1]);
hpPointer.setY(results[0]);
hpPointer.setArrowPaint(BLUE);
hpPointer.setTipRadius(7.0);
hpPointer.setBaseRadius(30.0);
hpPointer.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 10));
hpPointer.setPaint(BLUE);
bestTq = new XYDrawableAnnotation(results[3], results[2], 10, 10, cd);
tqPointer.setX(results[3]);
tqPointer.setY(results[2]);
tqPointer.setArrowPaint(YELLOW);
tqPointer.setTipRadius(7.0);
tqPointer.setBaseRadius(30.0);
tqPointer.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 10));
tqPointer.setPaint(YELLOW);
final XYTextAnnotation dynoResults = new XYTextAnnotation(resultStrings[1], xMin, yMin + (ySpace * 5));
dynoResults.setPaint(RED);
dynoResults.setTextAnchor(TextAnchor.BOTTOM_LEFT);
dynoResults.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14));
final XYTextAnnotation carText = new XYTextAnnotation(resultStrings[0], xMin, yMin + (ySpace * 4));
carText.setPaint(RED);
carText.setTextAnchor(TextAnchor.BOTTOM_LEFT);
carText.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 12));
final XYTextAnnotation stat1 = new XYTextAnnotation(resultStrings[2], xMin, yMin + (ySpace * 3));
stat1.setPaint(RED);
stat1.setTextAnchor(TextAnchor.BOTTOM_LEFT);
stat1.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 12));
final XYTextAnnotation stat2 = new XYTextAnnotation(resultStrings[3], xMin, yMin + ySpace * 2);
stat2.setPaint(RED);
stat2.setTextAnchor(TextAnchor.BOTTOM_LEFT);
stat2.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 12));
final XYTextAnnotation stat3 = new XYTextAnnotation(resultStrings[4], xMin, yMin + ySpace);
stat3.setPaint(RED);
stat3.setTextAnchor(TextAnchor.BOTTOM_LEFT);
stat3.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 12));
final XYTextAnnotation stat4 = new XYTextAnnotation(resultStrings[5], xMin, yMin);
stat4.setPaint(RED);
stat4.setTextAnchor(TextAnchor.BOTTOM_LEFT);
stat4.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 12));
if (!refStat.equals(" ")) {
refStat.setX(plot.getDomainAxis().getLowerBound() + 10);
refStat.setY(hpAxis.getUpperBound());
plot.addAnnotation(refStat);
}
rendererY1.addAnnotation(bestHp);
rendererY2.addAnnotation(bestTq);
rendererY1.addAnnotation(hpPointer);
rendererY2.addAnnotation(tqPointer);
plot.addAnnotation(dynoResults);
plot.addAnnotation(carText);
plot.addAnnotation(stat1);
plot.addAnnotation(stat2);
plot.addAnnotation(stat3);
plot.addAnnotation(stat4);
}Example 55
| Project: spatial_statistics_for_geotools_udig-master File: HistogramDialog.java View source code |
private void updateChart(SimpleFeatureCollection features, String field) {
int bin = spinner.getSelection();
double[] values = getValues(features, field);
HistogramDataset dataset = new HistogramDataset();
dataset.addSeries(field, values, bin, minMaxVisitor.getMinX(), minMaxVisitor.getMaxX());
dataset.setType(histogramType);
JFreeChart chart = ChartFactory.createHistogram(EMPTY, null, null, dataset, PlotOrientation.VERTICAL, false, false, false);
// 1. Create a single plot containing both the scatter and line
chart.setBackgroundPaint(java.awt.Color.WHITE);
chart.setBorderVisible(false);
XYPlot plot = (XYPlot) chart.getPlot();
plot.setForegroundAlpha(0.85F);
plot.setBackgroundPaint(java.awt.Color.WHITE);
plot.setOrientation(PlotOrientation.VERTICAL);
plot.setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY);
plot.setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
int fontStyle = java.awt.Font.BOLD;
FontData fontData = getShell().getDisplay().getSystemFont().getFontData()[0];
NumberAxis valueAxis = new NumberAxis(cboField.getText());
valueAxis.setLabelFont(new Font(fontData.getName(), fontStyle, 12));
valueAxis.setTickLabelFont(new Font(fontData.getName(), fontStyle, 10));
valueAxis.setAutoRange(false);
valueAxis.setRange(minMaxVisitor.getMinX(), minMaxVisitor.getMaxX());
//$NON-NLS-1$ //$NON-NLS-2$
String rangeAxisLabel = histogramType == HistogramType.FREQUENCY ? "Frequency" : "Ratio";
NumberAxis rangeAxis = new NumberAxis(rangeAxisLabel);
rangeAxis.setLabelFont(new Font(fontData.getName(), fontStyle, 12));
rangeAxis.setTickLabelFont(new Font(fontData.getName(), fontStyle, 10));
if (histogramType == HistogramType.FREQUENCY) {
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
}
XYBarRenderer renderer = (XYBarRenderer) plot.getRenderer();
renderer.setShadowVisible(false);
// init
CustomXYBarPainter.selectedColumn = -1;
renderer.setBarPainter(new CustomXYBarPainter());
renderer.setAutoPopulateSeriesFillPaint(true);
renderer.setAutoPopulateSeriesPaint(true);
renderer.setShadowXOffset(3);
renderer.setMargin(0.01);
renderer.setBaseItemLabelsVisible(true);
ItemLabelPosition pos = new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.TOP_CENTER);
renderer.setBasePositiveItemLabelPosition(pos);
XYToolTipGenerator plotToolTip = new StandardXYToolTipGenerator();
renderer.setBaseToolTipGenerator(plotToolTip);
// color
GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, java.awt.Color.GRAY, 0.0f, 0.0f, java.awt.Color.LIGHT_GRAY);
renderer.setSeriesPaint(0, gp0);
plot.setDomainAxis(0, valueAxis);
plot.setRangeAxis(0, rangeAxis);
// 3. Setup line
// Create the line data, renderer, and axis
// Lines only
XYItemRenderer lineRenderer = new XYLineAndShapeRenderer(true, false);
lineRenderer.setSeriesPaint(0, java.awt.Color.RED);
lineRenderer.setSeriesStroke(0, new BasicStroke(2f));
// Set the line data, renderer, and axis into plot
NumberAxis xLineAxis = new NumberAxis(EMPTY);
xLineAxis.setTickMarksVisible(false);
xLineAxis.setTickLabelsVisible(false);
xLineAxis.setAutoRange(false);
NumberAxis yLineAxis = new NumberAxis(EMPTY);
yLineAxis.setTickMarksVisible(false);
yLineAxis.setTickLabelsVisible(false);
yLineAxis.setAutoRange(false);
double maxYValue = Double.MIN_VALUE;
for (int i = 0; i < dataset.getItemCount(0); i++) {
maxYValue = Math.max(maxYValue, dataset.getYValue(0, i));
}
XYSeriesCollection lineDatset = new XYSeriesCollection();
// Vertical Average
//$NON-NLS-1$
XYSeries vertical = new XYSeries("Average");
vertical.add(minMaxVisitor.getAverageX(), 0);
vertical.add(minMaxVisitor.getAverageX(), maxYValue);
lineDatset.addSeries(vertical);
plot.setDataset(1, lineDatset);
plot.setRenderer(1, lineRenderer);
plot.setDomainAxis(1, xLineAxis);
plot.setRangeAxis(1, yLineAxis);
// Map the line to the second Domain and second Range
plot.mapDatasetToDomainAxis(1, 0);
plot.mapDatasetToRangeAxis(1, 0);
chartComposite.setChart(chart);
chartComposite.forceRedraw();
}Example 56
| Project: tdq-studio-se-master File: TopChartFactory.java View source code |
public static JFreeChart createBlockingBarChart(String title, HistogramDataset dataset) {
ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
JFreeChart chart = //$NON-NLS-1$
ChartFactory.createHistogram(//$NON-NLS-1$
null, //$NON-NLS-1$
title, //$NON-NLS-1$
"Key frequency", //$NON-NLS-1$
dataset, //$NON-NLS-1$
PlotOrientation.VERTICAL, //$NON-NLS-1$
false, true, false);
XYPlot plot = chart.getXYPlot();
plot.getRangeAxis().setUpperMargin(0.08);
// plot.getRangeAxis().setLowerBound(-0.08);
decorateCategoryPlot(chart);
plot.setRangeGridlinesVisible(true);
XYBarRenderer renderer = new XYBarRenderer() {
private static final long serialVersionUID = 4168794048090452033L;
@Override
public Paint getItemPaint(int row, int column) {
return ChartDecorator.COLOR_LIST.get(0);
}
};
renderer.setBaseItemLabelsVisible(true);
renderer.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
renderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
renderer.setShadowVisible(Boolean.FALSE);
plot.setRenderer(renderer);
return chart;
}Example 57
| Project: trade-manager-master File: PivotRenderer.java View source code |
/**
* Draws the annotation.
*
* @param g2
* the graphics device.
* @param plot
* the plot.
* @param dataArea
* the data area.
* @param domainAxis
* the domain axis.
* @param rangeAxis
* the range axis.
* @param rendererIndex
* the renderer index.
* @param info
* the plot rendering info.
* @param angle
* double
* @param x
* double
* @param y
* double
* @param ledgend
* String
*/
public void drawPivotArrow(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis, int rendererIndex, PlotRenderingInfo info, double angle, double x, double y, String ledgend) {
double tipRadius = DEFAULT_TIP_RADIUS;
double baseRadius = DEFAULT_BASE_RADIUS;
double arrowLength = DEFAULT_ARROW_LENGTH;
double arrowWidth = DEFAULT_ARROW_WIDTH;
double labelOffset = DEFAULT_LABEL_OFFSET;
Font font = DEFAULT_FONT;
Paint paint = DEFAULT_PAINT;
boolean outlineVisible = false;
Paint outlinePaint = Color.black;
Stroke outlineStroke = new BasicStroke(0.5f);
TextAnchor textAnchor = DEFAULT_TEXT_ANCHOR;
TextAnchor rotationAnchor = DEFAULT_ROTATION_ANCHOR;
double rotationAngle = DEFAULT_ROTATION_ANGLE;
Stroke arrowStroke = new BasicStroke(1.0f);
Paint arrowPaint = Color.black;
PlotOrientation orientation = plot.getOrientation();
RectangleEdge domainEdge = Plot.resolveDomainAxisLocation(plot.getDomainAxisLocation(), orientation);
RectangleEdge rangeEdge = Plot.resolveRangeAxisLocation(plot.getRangeAxisLocation(), orientation);
double j2DX = domainAxis.valueToJava2D(x, dataArea, domainEdge);
double j2DY = rangeAxis.valueToJava2D(y, dataArea, rangeEdge);
if (orientation == PlotOrientation.HORIZONTAL) {
double temp = j2DX;
j2DX = j2DY;
j2DY = temp;
}
double startX = j2DX + (Math.cos(angle) * baseRadius);
double startY = j2DY + (Math.sin(angle) * baseRadius);
double endX = j2DX + (Math.cos(angle) * tipRadius);
double endY = j2DY + (Math.sin(angle) * tipRadius);
double arrowBaseX = endX + (Math.cos(angle) * arrowLength);
double arrowBaseY = endY + (Math.sin(angle) * arrowLength);
double arrowLeftX = arrowBaseX + (Math.cos(angle + (Math.PI / 2.0)) * arrowWidth);
double arrowLeftY = arrowBaseY + (Math.sin(angle + (Math.PI / 2.0)) * arrowWidth);
double arrowRightX = arrowBaseX - (Math.cos(angle + (Math.PI / 2.0)) * arrowWidth);
double arrowRightY = arrowBaseY - (Math.sin(angle + (Math.PI / 2.0)) * arrowWidth);
GeneralPath arrow = new GeneralPath();
arrow.moveTo((float) endX, (float) endY);
arrow.lineTo((float) arrowLeftX, (float) arrowLeftY);
arrow.lineTo((float) arrowRightX, (float) arrowRightY);
arrow.closePath();
g2.setStroke(arrowStroke);
g2.setPaint(arrowPaint);
Line2D line = new Line2D.Double(startX, startY, endX, endY);
g2.draw(line);
g2.fill(arrow);
// draw the label
double labelX = j2DX + (Math.cos(angle) * (baseRadius + labelOffset));
double labelY = j2DY + (Math.sin(angle) * (baseRadius + labelOffset));
g2.setFont(font);
Shape hotspot = TextUtilities.calculateRotatedStringBounds(ledgend, g2, (float) labelX, (float) labelY, textAnchor, rotationAngle, rotationAnchor);
g2.setPaint(paint);
TextUtilities.drawRotatedString(ledgend, g2, (float) labelX, (float) labelY, textAnchor, rotationAngle, rotationAnchor);
if (outlineVisible) {
g2.setStroke(outlineStroke);
g2.setPaint(outlinePaint);
g2.draw(hotspot);
}
// String toolTip = getToolTipText();
// String url = getURL();
// if (toolTip != null || url != null) {
// addEntity(info, hotspot, rendererIndex, toolTip, url);
// }
}Example 58
| Project: zaproxy-master File: ScanProgressDialog.java View source code |
/**
* Updates the scan progress shown by the dialogue (scanners' progress/state and chart).
*/
private void updateProgress() {
// Start panel data settings
HostProcess hp = getSelectedHostProcess();
if (scan.getHostProcesses() != null && hp != null) {
// Update the main table entries
model.updateValues(scan, hp);
if (scan.isStopped()) {
this.stopThread = true;
}
if (chart != null) {
ResponseCountSnapshot snapshot = scan.getRequestHistory();
while (snapshot != null) {
try {
Second second = new Second(snapshot.getDate());
this.seriesTotal.add(second, snapshot.getTotal());
this.series100.add(second, snapshot.getResp100());
this.series200.add(second, snapshot.getResp200());
this.series300.add(second, snapshot.getResp300());
this.series400.add(second, snapshot.getResp400());
this.series500.add(second, snapshot.getResp500());
snapshot = scan.getRequestHistory();
for (Plugin plugin : scan.getHostProcesses().get(0).getRunning()) {
if (!labelsAdded.contains(plugin.getName())) {
// Add a vertical line with the plugin name
ValueMarker vm = new ValueMarker(plugin.getTimeStarted().getTime());
double center = chart.getXYPlot().getRangeAxis().getRange().getCentralValue();
if (lastCentre != center) {
if (lastCentre != -1) {
// Move the existing labels so they stay in the centre
@SuppressWarnings("rawtypes") List annotations = chart.getXYPlot().getAnnotations();
for (Object o : annotations) {
if (o instanceof XYTextAnnotation) {
XYTextAnnotation annotation = (XYTextAnnotation) o;
annotation.setY(center);
}
}
}
lastCentre = center;
}
XYTextAnnotation updateLabel = new XYTextAnnotation(plugin.getName(), plugin.getTimeStarted().getTime(), center);
updateLabel.setFont(FontUtils.getFont("Sans Serif"));
updateLabel.setRotationAnchor(TextAnchor.BASELINE_CENTER);
updateLabel.setTextAnchor(TextAnchor.BASELINE_CENTER);
updateLabel.setRotationAngle(-3.14 / 2);
updateLabel.setPaint(Color.black);
chart.getXYPlot().addDomainMarker(vm, Layer.BACKGROUND);
chart.getXYPlot().addAnnotation(updateLabel);
labelsAdded.add(plugin.getName());
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
snapshot = null;
}
}
}
}
}Example 59
| Project: agile-itsm-master File: GerencialGenerateEjb.java View source code |
private Object generateRetornoGrafico_Barra(boolean is3D, List listRetorno, GerencialItemInformationDTO gerencialItemDto, GerencialInfoGenerateDTO infoGenerate, Usuario usuario, GerencialItemPainelDTO gerencialItemPainelAuxDto, HttpServletRequest request) throws Exception {
JFreeChart chart;
DefaultCategoryDataset dados = new DefaultCategoryDataset();
Double objDouble;
String objString1;
String objString2;
int qtdeColunas = 0;
int posString = 0;
int qtdeLinhas = 0;
for (int i = 0; i < listRetorno.size(); i++) {
Object[] row = (Object[]) listRetorno.get(i);
qtdeColunas = row.length - 1;
objDouble = new Double(0);
objString1 = "";
objString2 = "";
posString = 0;
qtdeLinhas++;
for (int j = 0; j < row.length; j++) {
Object obj = row[j];
GerencialFieldDTO fieldDto = (GerencialFieldDTO) ((List) gerencialItemDto.getListFields()).get(j);
if (fieldDto.getClassField().getName().equalsIgnoreCase("java.lang.Integer")) {
if (Integer.class.isInstance(obj)) {
objDouble = new Double(((Integer) obj).intValue());
} else if (Long.class.isInstance(obj)) {
objDouble = new Double(((Long) obj).intValue());
}
}
if (fieldDto.getClassField().getName().equalsIgnoreCase("java.lang.Double")) {
objDouble = null;
if (Integer.class.isInstance(obj)) {
objDouble = new Double(((Integer) obj).doubleValue());
} else {
if (BigDecimal.class.isInstance(obj)) {
objDouble = new Double(((BigDecimal) obj).doubleValue());
} else if (Long.class.isInstance(obj)) {
objDouble = new Double(((Long) obj).doubleValue());
} else if (Integer.class.isInstance(obj)) {
objDouble = new Double(((Integer) obj).doubleValue());
} else if (BigInteger.class.isInstance(obj)) {
objDouble = new Double(((BigInteger) obj).doubleValue());
} else {
objDouble = (Double) obj;
}
}
if (objDouble == null) {
objDouble = new Double(0);
}
}
if (fieldDto.getClassField().getName().equalsIgnoreCase("java.lang.String")) {
if (obj == null) {
obj = new String("");
}
String str = "";
if (Integer.class.isInstance(obj)) {
str = "" + (Integer) obj;
} else {
str = (String) obj;
}
if (posString == 0) {
objString1 = str;
} else {
objString2 = str;
}
posString++;
}
}
if (objString1 == null || objString1.trim().equalsIgnoreCase("")) {
Object obj = row[0];
GerencialFieldDTO fieldDto = (GerencialFieldDTO) ((List) gerencialItemDto.getListFields()).get(0);
if (fieldDto.getClassField().getName().equalsIgnoreCase("java.lang.Integer")) {
objString1 = new String("" + ((Integer) obj).intValue());
}
if (fieldDto.getClassField().getName().equalsIgnoreCase("java.lang.Double")) {
objDouble = null;
if (Integer.class.isInstance(obj)) {
objDouble = new Double(((Integer) obj).doubleValue());
} else {
if (BigDecimal.class.isInstance(obj)) {
objDouble = new Double(((BigDecimal) obj).doubleValue());
} else if (Long.class.isInstance(obj)) {
objDouble = new Double(((Long) obj).doubleValue());
} else if (Integer.class.isInstance(obj)) {
objDouble = new Double(((Integer) obj).doubleValue());
} else if (BigInteger.class.isInstance(obj)) {
objDouble = new Double(((BigInteger) obj).doubleValue());
} else {
objDouble = (Double) obj;
}
}
if (objDouble == null) {
objDouble = new Double(0);
}
objString1 = UtilFormatacao.formatDouble(objDouble, 0);
}
}
dados.addValue(objDouble.doubleValue(), objString1, objString2);
}
String t1 = null;
String t2 = null;
GerencialFieldDTO fieldDto = null;
try {
fieldDto = (GerencialFieldDTO) ((List) gerencialItemDto.getListFields()).get(0);
t1 = fieldDto.getTitle();
} catch (Exception e) {
}
try {
fieldDto = (GerencialFieldDTO) ((List) gerencialItemDto.getListFields()).get(qtdeColunas);
t2 = fieldDto.getTitle();
} catch (Exception e) {
}
if (is3D) {
chart = ChartFactory.createBarChart3D(UtilI18N.internacionaliza(request, gerencialItemDto.getTitle()), t1, t2, dados, PlotOrientation.VERTICAL, true, true, false);
} else {
chart = ChartFactory.createBarChart(UtilI18N.internacionaliza(request, gerencialItemDto.getTitle()), t1, t2, dados, PlotOrientation.VERTICAL, true, true, false);
}
// Setando o valor maximo para nunca passar de 100, ja q se trata de
// porcentagem
CategoryPlot plot = chart.getCategoryPlot();
plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
plot.getRenderer().setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE1, TextAnchor.CENTER));
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setUpperMargin(0.20);
rangeAxis.setAxisLineVisible(true);
rangeAxis.setTickLabelsVisible(true);
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
// Formatando cores de fundo, fonte do titulo, etc...
// Cor do fundo do grafico
chart.setBackgroundPaint(COR_FUNDO);
// Cor do titulo
chart.getTitle().setPaint(COR_TITULO);
// Fonte do
chart.getTitle().setFont(new java.awt.Font("arial", Font.BOLD, 10));
// Cor de
chart.getPlot().setBackgroundPaint(new Color(221, 227, 213));
chart.getLegend().setItemFont(new java.awt.Font("arial", Font.BOLD, 8));
// Visibilidade da borda do grafico
chart.setBorderVisible(false);
BarRenderer rend = (BarRenderer) plot.getRenderer();
// CategoryItemRenderer rend = (CategoryItemRenderer) plot.getRenderer();
// Cor da borda das barras do
rend.setSeriesOutlinePaint(0, Color.BLACK);
rend.setBaseItemLabelFont(new java.awt.Font("SansSerif", Font.BOLD, 10));
// rend.setSeriesPaint(0, new Color(70 ,130 ,180)); // Cor das barras do
// rend.setItemMargin(0.10); // Margem entre o eixo Y e a primeira barra do
rend.setBaseItemLabelsVisible(true);
// rend.setBaseItemLabelGenerator(new CustomLabelGenerator());
rend.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
rend.setSeriesItemLabelsVisible(0, new Boolean(true));
rend.setSeriesItemLabelGenerator(0, new StandardCategoryItemLabelGenerator());
// rend.setSeriesPositiveItemLabelPosition(1, new ItemLabelPosition(ItemLabelAnchor.OUTSIDE11, TextAnchor.BASELINE_CENTER, TextAnchor.BASELINE_CENTER, 50.0));
rend.setPositiveItemLabelPositionFallback(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.BASELINE_CENTER, TextAnchor.CENTER, 0.0));
String caminhoRelativo = "";
String caminho = "";
try {
File arquivo = new File(infoGenerate.getCaminhoArquivosGraficos());
if (!arquivo.exists()) {
arquivo.mkdirs();
}
File arquivoVer = new File(infoGenerate.getCaminhoArquivosGraficos() + "/" + usuario.getIdUsuario());
if (!arquivoVer.exists()) {
arquivoVer.mkdirs();
}
caminho = infoGenerate.getCaminhoArquivosGraficos() + "/" + usuario.getIdUsuario() + "/" + UtilStrings.generateNomeBusca(UtilStrings.removeCaracteresEspeciais(gerencialItemDto.getDescription())) + "_" + UtilDatas.convertDateToString(TipoDate.TIMESTAMP_WITH_SECONDS, UtilDatas.getDataHoraAtual(), WebUtil.getLanguage(request)).replaceAll("/", "_").replaceAll(":", "_").replaceAll(" ", "_") + ".png";
// caminhoRelativo = br.com.citframework.util.Constantes.getValue("SERVER_ADDRESS") + br.com.citframework.util.Constantes.getValue("CONTEXTO_APLICACAO") + "/tempFiles" + "/" +
// usuario.getIdUsuario() + "/" + UtilStrings.generateNomeBusca(UtilStrings.removeCaracteresEspeciais(gerencialItemDto.getDescription())) + "_" +
// UtilDatas.formatTimestamp(UtilDatas.getDataHoraAtual()).replaceAll("/", "_").replaceAll(":", "_").replaceAll(" ", "_") + ".png";
String urlInicial = "";
if (urlInicial == null || urlInicial.trim().equalsIgnoreCase("")) {
urlInicial = Constantes.getValue("CONTEXTO_APLICACAO");
}
caminhoRelativo = urlInicial + "/tempFiles" + "/" + usuario.getIdUsuario() + "/" + UtilStrings.generateNomeBusca(UtilStrings.removeCaracteresEspeciais(gerencialItemDto.getDescription())) + "_" + UtilDatas.convertDateToString(TipoDate.TIMESTAMP_WITH_SECONDS, UtilDatas.getDataHoraAtual(), WebUtil.getLanguage(request)).replaceAll("/", "_").replaceAll(":", "_").replaceAll(" ", "_") + ".png";
caminhoRelativoAuxiliar = caminhoRelativo;
arquivo = new File(caminho);
if (arquivo.exists()) {
arquivo.delete();
}
int tam = Integer.parseInt(UtilStrings.apenasNumeros(gerencialItemPainelAuxDto.getWidth()));
int alt = Integer.parseInt(UtilStrings.apenasNumeros(gerencialItemPainelAuxDto.getHeigth()));
tam = tam - 15;
alt = alt - 70;
/*
* if (qtdeLinhas > 20){ tam = qtdeLinhas * 18; }
*/
ChartUtilities.saveChartAsPNG(arquivo, chart, tam, alt);
LOGGER.info("Grafico de Barras gerado em:\n\t" + caminho);
} catch (IOException e) {
LOGGER.error("Problemas durante a criação do Gráfico de Barras.", e);
}
if (listRetorno != null && listRetorno.size() != 0) {
return "<img src=\"" + caminhoRelativo + "\"/>";
} else {
return null;
}
}Example 60
| Project: ControlAndroidDeviceFromPC-master File: NetworkPanel.java View source code |
/**
* Create chart of recent network activity.
*/
private void createChart() {
mChart = ChartFactory.createTimeSeriesChart(null, null, null, null, false, false, false);
// create backing datasets and series
mRxTotalSeries = new TimeSeries("RX total");
mTxTotalSeries = new TimeSeries("TX total");
mRxTotalSeries.setMaximumItemAge(HISTORY_MILLIS);
mTxTotalSeries.setMaximumItemAge(HISTORY_MILLIS);
mTotalCollection = new TimeSeriesCollection();
mTotalCollection.addSeries(mRxTotalSeries);
mTotalCollection.addSeries(mTxTotalSeries);
mRxDetailDataset = new LiveTimeTableXYDataset();
mTxDetailDataset = new LiveTimeTableXYDataset();
mTotalRenderer = new XYAreaRenderer(XYAreaRenderer.AREA);
mRenderer = new StackedXYAreaRenderer2();
final XYPlot xyPlot = mChart.getXYPlot();
xyPlot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
xyPlot.setDataset(0, mTotalCollection);
xyPlot.setDataset(1, mRxDetailDataset);
xyPlot.setDataset(2, mTxDetailDataset);
xyPlot.setRenderer(0, mTotalRenderer);
xyPlot.setRenderer(1, mRenderer);
xyPlot.setRenderer(2, mRenderer);
// we control domain axis manually when taking samples
mDomainAxis = xyPlot.getDomainAxis();
mDomainAxis.setAutoRange(false);
final NumberAxis axis = new NumberAxis();
axis.setNumberFormatOverride(new BytesFormat(true));
axis.setAutoRangeMinimumSize(50);
xyPlot.setRangeAxis(axis);
xyPlot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
// draw thick line to separate RX versus TX traffic
xyPlot.addRangeMarker(new ValueMarker(0, java.awt.Color.BLACK, new java.awt.BasicStroke(2)));
// label to indicate that positive axis is RX traffic
final ValueMarker rxMarker = new ValueMarker(0);
rxMarker.setStroke(new java.awt.BasicStroke(0));
rxMarker.setLabel("RX");
rxMarker.setLabelFont(rxMarker.getLabelFont().deriveFont(30f));
rxMarker.setLabelPaint(java.awt.Color.LIGHT_GRAY);
rxMarker.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
rxMarker.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT);
xyPlot.addRangeMarker(rxMarker);
// label to indicate that negative axis is TX traffic
final ValueMarker txMarker = new ValueMarker(0);
txMarker.setStroke(new java.awt.BasicStroke(0));
txMarker.setLabel("TX");
txMarker.setLabelFont(txMarker.getLabelFont().deriveFont(30f));
txMarker.setLabelPaint(java.awt.Color.LIGHT_GRAY);
txMarker.setLabelAnchor(RectangleAnchor.BOTTOM_RIGHT);
txMarker.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
xyPlot.addRangeMarker(txMarker);
mChartComposite = new ChartComposite(mPanel, SWT.BORDER, mChart, ChartComposite.DEFAULT_WIDTH, ChartComposite.DEFAULT_HEIGHT, ChartComposite.DEFAULT_MINIMUM_DRAW_WIDTH, ChartComposite.DEFAULT_MINIMUM_DRAW_HEIGHT, 4096, 4096, true, true, true, true, false, true);
final FormData data = new FormData();
data.top = new FormAttachment(mHeader);
data.left = new FormAttachment(0);
data.bottom = new FormAttachment(70);
data.right = new FormAttachment(100);
mChartComposite.setLayoutData(data);
}Example 61
| Project: FlightPlot-master File: FlightPlot.java View source code |
private void generateSeries() throws IOException, FormatErrorException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
activeProcessors.clear();
activeProcessors.addAll(getActiveProcessors());
dataset.removeAllSeries();
seriesIndex.clear();
PlotProcessor[] processors = new PlotProcessor[activeProcessors.size()];
// Update time offset according to selected time mode
long timeOffset = getTimeOffset(timeMode);
// Displayed log range in seconds of native log time
Range range = getLogRange(timeMode);
// Process some extra data in hidden areas
long timeStart = (long) ((range.getLowerBound() - range.getLength()) * 1e6);
long timeStop = (long) ((range.getUpperBound() + range.getLength()) * 1e6);
timeStart = Math.max(logReader.getStartMicroseconds(), timeStart);
timeStop = Math.min(logReader.getStartMicroseconds() + logReader.getSizeMicroseconds(), timeStop);
double timeScale = (selectDomainAxis(timeMode) == domainAxisDate) ? 1000.0 : 1.0;
int displayPixels = 2000;
double skip = range.getLength() / displayPixels;
if (processors.length > 0) {
for (int i = 0; i < activeProcessors.size(); i++) {
ProcessorPreset pp = activeProcessors.get(i);
PlotProcessor processor;
processor = processorsTypesList.getProcessorInstance(pp, skip, logReader.getFields());
processor.setFieldsList(logReader.getFields());
processors[i] = processor;
}
logReader.seek(timeStart);
logReader.clearErrors();
Map<String, Object> data = new HashMap<String, Object>();
while (true) {
long t;
data.clear();
try {
t = logReader.readUpdate(data);
} catch (EOFException e) {
break;
}
if (t > timeStop) {
break;
}
for (PlotProcessor processor : processors) {
processor.process((t + timeOffset) * 1e-6, data);
}
}
chart.getXYPlot().clearDomainMarkers();
for (int i = 0; i < activeProcessors.size(); i++) {
PlotProcessor processor = processors[i];
String processorTitle = activeProcessors.get(i).getTitle();
Map<String, Integer> processorSeriesIndex = new HashMap<String, Integer>();
seriesIndex.add(processorSeriesIndex);
for (PlotItem item : processor.getSeriesList()) {
if (item instanceof Series) {
Series series = (Series) item;
processorSeriesIndex.put(series.getTitle(), dataset.getSeriesCount());
XYSeries jseries = new XYSeries(series.getFullTitle(processorTitle), false);
for (XYPoint point : series) {
jseries.add(point.x * timeScale, point.y, false);
}
dataset.addSeries(jseries);
} else if (item instanceof MarkersList) {
MarkersList markers = (MarkersList) item;
processorSeriesIndex.put(markers.getTitle(), dataset.getSeriesCount());
XYSeries jseries = new XYSeries(markers.getFullTitle(processorTitle), false);
dataset.addSeries(jseries);
for (Marker marker : markers) {
TaggedValueMarker m = new TaggedValueMarker(i, marker.x * timeScale);
m.setPaint(Color.black);
m.setLabel(marker.label);
m.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
m.setLabelTextAnchor(TextAnchor.TOP_LEFT);
chart.getXYPlot().addDomainMarker(0, m, Layer.BACKGROUND, false);
}
}
}
}
setChartColors();
setChartMarkers();
}
chartPanel.repaint();
}Example 62
| Project: grammarviz2_src-master File: GrammarvizChartPanel.java View source code |
/**
* Puts rules density on show.
*/
private void displayRuleDensity() {
// this is the new "insert" - elastic boundaries chart panel
//
// paintTheChart(this.session.chartData.getOriginalTimeseries());
// chartPanel = new ChartPanel(this.chart);
// chartPanel.setMaximumDrawHeight(this.getParent().getHeight());
// chartPanel.setMaximumDrawWidth(this.getParent().getWidth());
// chartPanel.setMinimumDrawWidth(0);
// chartPanel.setMinimumDrawHeight(0);
// chartPanel.revalidate();
//
this.removeAll();
this.add(chartPanel);
// init vars
//
int maxObservedCoverage = Integer.MIN_VALUE;
int minObservedCoverage = Integer.MAX_VALUE;
int[] coverageArray = new int[this.session.chartData.getOriginalTimeseries().length];
for (GrammarRuleRecord r : this.session.chartData.getGrammarRules()) {
if (0 == r.ruleNumber()) {
// skip R0
continue;
}
ArrayList<RuleInterval> occurrences = this.session.chartData.getRulePositionsByRuleNum(r.ruleNumber());
for (RuleInterval i : occurrences) {
int start = i.getStart();
int end = i.getEnd();
for (int j = start; j < end; j++) {
if (CoverageCountStrategy.COUNT.equals(this.session.countStrategy)) {
coverageArray[j] = coverageArray[j] + 1;
} else if (CoverageCountStrategy.LEVEL.equals(this.session.countStrategy)) {
coverageArray[j] = coverageArray[j] + r.getRuleLevel();
} else if (CoverageCountStrategy.OCCURRENCE.equals(this.session.countStrategy)) {
coverageArray[j] = coverageArray[j] + r.getOccurrences().size();
} else if (CoverageCountStrategy.YIELD.equals(this.session.countStrategy)) {
coverageArray[j] = coverageArray[j] + r.getRuleYield();
} else if (CoverageCountStrategy.PRODUCT.equals(this.session.countStrategy)) {
coverageArray[j] = coverageArray[j] + r.getRuleLevel() * r.getOccurrences().size();
}
if (maxObservedCoverage < coverageArray[j]) {
maxObservedCoverage = coverageArray[j];
}
if (minObservedCoverage > coverageArray[j]) {
minObservedCoverage = coverageArray[j];
}
}
}
}
// since we know the maximal coverage value, we can compute the increment for a single coverage
// interval
double covIncrement = 1.0 / (double) maxObservedCoverage;
for (GrammarRuleRecord r : this.session.chartData.getGrammarRules()) {
if (0 == r.ruleNumber()) {
// skip the R0
continue;
}
ArrayList<RuleInterval> occurrences = r.getRuleIntervals();
for (RuleInterval i : occurrences) {
IntervalMarker marker = new IntervalMarker(i.getStart(), i.getEnd());
marker.setLabelOffsetType(LengthAdjustmentType.EXPAND);
marker.setPaint(Color.BLUE);
// marker.setAlpha((float) 0.05);
if (CoverageCountStrategy.COUNT.equals(this.session.countStrategy)) {
marker.setAlpha((float) covIncrement);
} else if (CoverageCountStrategy.LEVEL.equals(this.session.countStrategy)) {
marker.setAlpha((float) covIncrement * r.getRuleLevel());
} else if (CoverageCountStrategy.OCCURRENCE.equals(this.session.countStrategy)) {
marker.setAlpha((float) covIncrement * r.getOccurrences().size());
} else if (CoverageCountStrategy.YIELD.equals(this.session.countStrategy)) {
marker.setAlpha((float) covIncrement * r.getRuleYield());
} else if (CoverageCountStrategy.PRODUCT.equals(this.session.countStrategy)) {
marker.setAlpha((float) covIncrement * (r.getRuleLevel() * r.getOccurrences().size()));
}
marker.setLabelFont(new Font("SansSerif", Font.PLAIN, 12));
marker.setLabelPaint(Color.green);
marker.setLabelAnchor(RectangleAnchor.TOP_LEFT);
marker.setLabelTextAnchor(TextAnchor.TOP_LEFT);
timeseriesPlot.addDomainMarker(marker, Layer.BACKGROUND);
}
}
int sum = 0;
for (int d : coverageArray) sum += d;
double meanCoverage = 1.0d * sum / coverageArray.length;
DecimalFormat df = new DecimalFormat("#.00");
String annotationString = "min C:" + minObservedCoverage + ", max C:" + maxObservedCoverage + ", mean C:" + df.format(meanCoverage);
NumberAxis domain = (NumberAxis) this.timeseriesPlot.getDomainAxis();
Range domainRange = domain.getRange();
NumberAxis range = (NumberAxis) this.timeseriesPlot.getRangeAxis();
Range rangeRange = range.getRange();
XYTextAnnotation a = new XYTextAnnotation(annotationString, domainRange.getLowerBound() + domainRange.getLength() / 100, rangeRange.getLowerBound() + 0.5);
a.setTextAnchor(TextAnchor.BOTTOM_LEFT);
a.setPaint(Color.RED);
a.setOutlinePaint(Color.BLACK);
a.setOutlineVisible(true);
a.setFont(new java.awt.Font("SansSerif", java.awt.Font.BOLD, 14));
this.timeseriesPlot.addAnnotation(a);
// not sure if I need this
//
revalidate();
repaint();
// and finally save the coverage curve
//
this.saveRuleDensityCurve(coverageArray);
}Example 63
| Project: limpet-master File: ChartBuilder.java View source code |
/**
*
* @param subplot
* target plot for annotation
* @param annotations
* annotation list to be added to plot eg: Marker,Zone
* @param isRangeAnnotation
* is annotation added to Range or Domain
*/
private static void addAnnotationToPlot(final XYPlot subplot, final List<AbstractAnnotation> annotations, final boolean isRangeAnnotation) {
for (final AbstractAnnotation annotation : annotations) {
final Color color = annotation.getColor();
if (annotation instanceof info.limpet.stackedcharts.model.Marker) {
// build value Marker
final info.limpet.stackedcharts.model.Marker marker = (info.limpet.stackedcharts.model.Marker) annotation;
final Marker mrk = new ValueMarker(marker.getValue());
mrk.setLabel(annotation.getName());
mrk.setPaint(color == null ? Color.GRAY : color);
// move Text Anchor
mrk.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
mrk.setLabelAnchor(RectangleAnchor.TOP);
mrk.setLabelOffset(new RectangleInsets(2, 2, 2, 2));
if (isRangeAnnotation) {
subplot.addRangeMarker(mrk, Layer.FOREGROUND);
} else {
subplot.addDomainMarker(mrk, Layer.FOREGROUND);
}
} else if (annotation instanceof info.limpet.stackedcharts.model.Zone) {
// build Zone
final info.limpet.stackedcharts.model.Zone zone = (info.limpet.stackedcharts.model.Zone) annotation;
final Marker mrk = new IntervalMarker(zone.getStart(), zone.getEnd());
mrk.setLabel(annotation.getName());
if (color != null) {
mrk.setPaint(color);
}
// move Text & Label Anchor
mrk.setLabelTextAnchor(TextAnchor.CENTER);
mrk.setLabelAnchor(RectangleAnchor.CENTER);
mrk.setLabelOffset(new RectangleInsets(2, 2, 2, 2));
if (isRangeAnnotation) {
subplot.addRangeMarker(mrk, Layer.FOREGROUND);
} else {
subplot.addDomainMarker(mrk, Layer.FOREGROUND);
}
} else if (annotation instanceof info.limpet.stackedcharts.model.ScatterSet) {
// build ScatterSet
final info.limpet.stackedcharts.model.ScatterSet marker = (info.limpet.stackedcharts.model.ScatterSet) annotation;
final EList<Datum> datums = marker.getDatums();
boolean addLabel = true;
for (final Datum datum : datums) {
final Marker mrk = new ValueMarker(datum.getVal());
// only add label for first Marker
if (addLabel) {
mrk.setLabel(annotation.getName());
addLabel = false;
}
final Color thisColor = datum.getColor();
final Color colorToUse = thisColor == null ? color : thisColor;
// apply some transparency to the color
if (colorToUse != null) {
final Color transColor = new Color(colorToUse.getRed(), colorToUse.getGreen(), colorToUse.getBlue(), 120);
mrk.setPaint(transColor);
}
// move Text Anchor
mrk.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
mrk.setLabelAnchor(RectangleAnchor.TOP);
mrk.setLabelOffset(new RectangleInsets(2, 2, 2, 2));
if (isRangeAnnotation) {
subplot.addRangeMarker(mrk, Layer.FOREGROUND);
} else {
subplot.addDomainMarker(mrk, Layer.FOREGROUND);
}
}
}
}
}Example 64
| Project: optaplanner-master File: BenchmarkReport.java View source code |
private BarRenderer createBarChartRenderer(NumberFormat numberFormat) {
BarRenderer renderer = new BarRenderer();
ItemLabelPosition positiveItemLabelPosition = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER);
renderer.setBasePositiveItemLabelPosition(positiveItemLabelPosition);
ItemLabelPosition negativeItemLabelPosition = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6, TextAnchor.TOP_CENTER);
renderer.setBaseNegativeItemLabelPosition(negativeItemLabelPosition);
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator(StandardCategoryItemLabelGenerator.DEFAULT_LABEL_FORMAT_STRING, numberFormat));
renderer.setBaseItemLabelsVisible(true);
return renderer;
}Example 65
| Project: platform_sdk-master File: NetworkPanel.java View source code |
/**
* Create chart of recent network activity.
*/
private void createChart() {
mChart = ChartFactory.createTimeSeriesChart(null, null, null, null, false, false, false);
// create backing datasets and series
mRxTotalSeries = new TimeSeries("RX total");
mTxTotalSeries = new TimeSeries("TX total");
mRxTotalSeries.setMaximumItemAge(HISTORY_MILLIS);
mTxTotalSeries.setMaximumItemAge(HISTORY_MILLIS);
mTotalCollection = new TimeSeriesCollection();
mTotalCollection.addSeries(mRxTotalSeries);
mTotalCollection.addSeries(mTxTotalSeries);
mRxDetailDataset = new LiveTimeTableXYDataset();
mTxDetailDataset = new LiveTimeTableXYDataset();
mTotalRenderer = new XYAreaRenderer(XYAreaRenderer.AREA);
mRenderer = new StackedXYAreaRenderer2();
final XYPlot xyPlot = mChart.getXYPlot();
xyPlot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
xyPlot.setDataset(0, mTotalCollection);
xyPlot.setDataset(1, mRxDetailDataset);
xyPlot.setDataset(2, mTxDetailDataset);
xyPlot.setRenderer(0, mTotalRenderer);
xyPlot.setRenderer(1, mRenderer);
xyPlot.setRenderer(2, mRenderer);
// we control domain axis manually when taking samples
mDomainAxis = xyPlot.getDomainAxis();
mDomainAxis.setAutoRange(false);
final NumberAxis axis = new NumberAxis();
axis.setNumberFormatOverride(new BytesFormat(true));
axis.setAutoRangeMinimumSize(50);
xyPlot.setRangeAxis(axis);
xyPlot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
// draw thick line to separate RX versus TX traffic
xyPlot.addRangeMarker(new ValueMarker(0, java.awt.Color.BLACK, new java.awt.BasicStroke(2)));
// label to indicate that positive axis is RX traffic
final ValueMarker rxMarker = new ValueMarker(0);
rxMarker.setStroke(new java.awt.BasicStroke(0));
rxMarker.setLabel("RX");
rxMarker.setLabelFont(rxMarker.getLabelFont().deriveFont(30f));
rxMarker.setLabelPaint(java.awt.Color.LIGHT_GRAY);
rxMarker.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
rxMarker.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT);
xyPlot.addRangeMarker(rxMarker);
// label to indicate that negative axis is TX traffic
final ValueMarker txMarker = new ValueMarker(0);
txMarker.setStroke(new java.awt.BasicStroke(0));
txMarker.setLabel("TX");
txMarker.setLabelFont(txMarker.getLabelFont().deriveFont(30f));
txMarker.setLabelPaint(java.awt.Color.LIGHT_GRAY);
txMarker.setLabelAnchor(RectangleAnchor.BOTTOM_RIGHT);
txMarker.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
xyPlot.addRangeMarker(txMarker);
mChartComposite = new ChartComposite(mPanel, SWT.BORDER, mChart, ChartComposite.DEFAULT_WIDTH, ChartComposite.DEFAULT_HEIGHT, ChartComposite.DEFAULT_MINIMUM_DRAW_WIDTH, ChartComposite.DEFAULT_MINIMUM_DRAW_HEIGHT, 4096, 4096, true, true, true, true, false, true);
final FormData data = new FormData();
data.top = new FormAttachment(mHeader);
data.left = new FormAttachment(0);
data.bottom = new FormAttachment(70);
data.right = new FormAttachment(100);
mChartComposite.setLayoutData(data);
}Example 66
| Project: sportstracker-master File: OverviewDialogController.java View source code |
/**
* Draws the Overview diagram according to the current selections.
*/
private void updateDiagram() {
updateOptionControls();
// get selected time range and value type and its name to display
TimeRangeType timeType = cbTimeRange.getValue();
ValueType vType = cbDisplay.getValue();
String valueTypeNameWithUnits = vType.getNameWithUnitSystem(context.getFormatUtils());
int year = spYear.getValue();
// create a table of all time series (graphs) and the appropriate colors
TimeTableXYDataset dataset = new TimeTableXYDataset();
java.util.List<java.awt.Color> lGraphColors = new ArrayList<>();
// setup TimeSeries in the diagram (done in different ways for all the value types)
if (vType == ValueType.SPORTSUBTYPE) {
setupSportSubTypeDiagram(dataset, lGraphColors);
} else if (vType == ValueType.EQUIPMENT) {
setupEquipmentDiagram(dataset, lGraphColors);
} else if (vType == ValueType.WEIGHT) {
setupWeightDiagram(dataset, lGraphColors);
} else {
setupExerciseDiagram(dataset, lGraphColors);
}
// create chart
JFreeChart chart = //
ChartFactory.createTimeSeriesChart(// Title
null, // Y-axis label
null, // X-axis label
valueTypeNameWithUnits, // primary dataset
dataset, // display legend
true, // display tooltips
true, // URLs
false);
// render unique filled shapes for each graph
XYPlot plot = (XYPlot) chart.getPlot();
XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
renderer.setBaseShapesVisible(true);
renderer.setBaseShapesFilled(true);
// set color for sport type series
for (int i = 0; i < lGraphColors.size(); i++) {
java.awt.Color tempColor = lGraphColors.get(i);
renderer.setSeriesPaint(i, tempColor);
}
// setup date format for tooltips and time (bottom) axis
String dateFormatTooltip;
String dateFormatAxis;
DateTickUnit dateTickUnit;
switch(timeType) {
case LAST_12_MONTHS:
dateFormatTooltip = "MMMMM yyyy";
dateFormatAxis = "MMM";
dateTickUnit = new DateTickUnit(DateTickUnitType.MONTH, 1);
break;
case MONTHS_OF_YEAR:
dateFormatTooltip = "MMMMM";
dateFormatAxis = "MMM";
dateTickUnit = new DateTickUnit(DateTickUnitType.MONTH, 1);
break;
case WEEKS_OF_YEAR:
// Workaround for a JFreeChart formating problem: years are used
// instead of weeks for the bottom axis, otherwise there will be
// format problems on the axis (the first week is often "52")
dateFormatTooltip = "yy";
dateFormatAxis = "yy";
dateTickUnit = new DateTickUnit(DateTickUnitType.YEAR, 2);
break;
default:
// LAST_10_YEARS
dateFormatTooltip = "yyyy";
dateFormatAxis = "yyyy";
dateTickUnit = new DateTickUnit(DateTickUnitType.YEAR, 1);
break;
}
// setup tooltips: must display month, week or year and the value only
String toolTipFormat = "{1}: {2}";
renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator(toolTipFormat, new SimpleDateFormat(dateFormatTooltip), new DecimalFormat()) {
@Override
public String generateToolTip(XYDataset dataset, int series, int item) {
return dataset.getSeriesKey(series) + ", " + super.generateToolTip(dataset, series, item);
}
});
// (only for exercises based value types, stacked mode can be selected only there)
if (cbSportTypeMode.isVisible() && cbSportTypeMode.getValue() == OverviewType.EACH_STACKED) {
renderer.setSeriesLinesVisible(0, false);
renderer.setSeriesShapesVisible(0, false);
renderer.setSeriesVisibleInLegend(0, false);
// actual dataset
dataset = new TimeTableXYDataset();
lGraphColors = new ArrayList<>();
// create a separate graph for each sport type
for (SportType sportType : document.getSportTypeList()) {
addExerciseTimeSeries(dataset, timeType, year, vType, sportType);
lGraphColors.add(ColorUtils.toAwtColor(sportType.getColor()));
}
plot.setDataset(1, dataset);
// actual stacked renderer
StackedRenderer stackedRenderer = new StackedRenderer();
// set color for sport type series
for (int i = 0; i < lGraphColors.size(); i++) {
java.awt.Color tempColor = lGraphColors.get(i);
stackedRenderer.setSeriesPaint(i, tempColor);
}
stackedRenderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator(toolTipFormat, new SimpleDateFormat(dateFormatTooltip), new DecimalFormat()) {
@Override
public String generateToolTip(XYDataset dataset, int series, int item) {
return dataset.getSeriesKey(series) + ", " + super.generateToolTip(dataset, series, item);
}
});
plot.setRenderer(1, stackedRenderer);
}
// set date format of time (bottom) axis
DateAxis axis = (DateAxis) plot.getDomainAxis();
axis.setDateFormatOverride(new SimpleDateFormat(dateFormatAxis));
if (dateTickUnit != null) {
axis.setTickUnit(dateTickUnit);
}
// (otherwise the range is double minimum to double maximum)
if (plot.getRangeAxis().getRange().getCentralValue() == 0d) {
plot.getRangeAxis().setRange(new Range(0, 10));
}
// add vertical year break marker when displaying the last 12 months
if (timeType == TimeRangeType.LAST_12_MONTHS) {
LocalDate firstDayOfYear = LocalDate.now().with(TemporalAdjusters.firstDayOfYear());
LocalDate middleOfDecemberOfLastYear = firstDayOfYear.minusDays(15);
Date dateMiddleOfDecemberOfLastYear = Date310Utils.localDateToDate(middleOfDecemberOfLastYear);
ValueMarker newYearMarker = new ValueMarker(dateMiddleOfDecemberOfLastYear.getTime());
newYearMarker.setPaint(new java.awt.Color(0x00b000));
newYearMarker.setStroke(new java.awt.BasicStroke(0.8f));
newYearMarker.setLabel(String.valueOf(firstDayOfYear.getYear()));
newYearMarker.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
newYearMarker.setLabelTextAnchor(TextAnchor.TOP_LEFT);
plot.addDomainMarker(newYearMarker);
}
// display legend next to the diagram on the right side
chart.getLegend().setPosition(RectangleEdge.RIGHT);
ChartUtils.customizeChart(chart);
// display chart in viewer (chart viewer will be initialized lazily)
if (chartViewer == null) {
chartViewer = new ChartViewer(chart);
spDiagram.getChildren().addAll(chartViewer);
} else {
chartViewer.setChart(chart);
}
}Example 67
| Project: Trackprofiler-master File: TrackProfilerFrame.java View source code |
private void _drawSelectedPoint(XYPlot xyplot, int position) {
TrackPoint point = this.getTrack().getPointAt(position);
// Strelicu crtamo samo ako je samo jedna tocka oznacena:
if (this.startSelectedPoints < 0 || this.endSelectedPoints < 0 || this.startSelectedPoints == this.endSelectedPoints) {
double angle = point.getAngle();
XYPointerAnnotation xypointerannotation = new //$NON-NLS-1$
XYPointerAnnotation(//$NON-NLS-1$
"", //$NON-NLS-1$
point.getPosition(), point.getElevation(), Math.PI - angle);
xypointerannotation.setTipRadius(3.0D);
xypointerannotation.setBaseRadius(30);
xypointerannotation.setTextAnchor(TextAnchor.BASELINE_RIGHT);
xypointerannotation.setFont(GUIConstants.SANS_SERIF_11);
if (angle > 0) {
xypointerannotation.setPaint(Color.red);
} else if (angle < 0) {
xypointerannotation.setPaint(Color.green);
} else {
xypointerannotation.setPaint(Color.gray);
}
//$NON-NLS-1$
xypointerannotation.setText((TrackProfilerMath.round(100 * angle, 1)) + " %");
xyplot.addAnnotation(xypointerannotation);
}
ValueMarker valuemarker = new ValueMarker(point.getPosition());
valuemarker.setLabelOffsetType(LengthAdjustmentType.NO_CHANGE);
valuemarker.setStroke(new BasicStroke(1.0F));
if (this.startSelectedPoints != this.endSelectedPoints && position == this.startSelectedPoints) {
valuemarker.setLabelPaint(Color.blue);
valuemarker.setLabelAnchor(RectangleAnchor.BOTTOM_LEFT);
valuemarker.setLabelTextAnchor(TextAnchor.BOTTOM_LEFT);
// Ispisuje udaljenost i kut:
TrackPoint t1 = this.getTrack().getPointAt(this.startSelectedPoints);
TrackPoint t2 = this.getTrack().getPointAt(this.endSelectedPoints);
double distance3D = TrackProfilerMath.round(t1.getPosition() - t2.getPosition(), 1);
//$NON-NLS-1$
String angle = Math.abs(TrackProfilerMath.round(t1.getAngle(t2) * 100, 1)) + "%";
//$NON-NLS-1$
String label = Message.get(Messages.SELECTED_DISTANCE_LABEL) + distance3D + ", " + Message.get(Messages.SELECTED_ANGLE_LABEL) + angle;
//$NON-NLS-1$
valuemarker.setLabel(" " + label);
valuemarker.setLabelFont(GUIConstants.SANS_SERIF_11);
}
xyplot.addDomainMarker(valuemarker);
}Example 68
| Project: bi-platform-v2-master File: JFreeChartEngine.java View source code |
private static JFreeChart createBarChart(final CategoryDatasetChartDefinition chartDefinition) {
// TODO Make the following accessible from the chartDefinition
String categoryAxisLabel = null;
String valueAxisLabel = null;
boolean tooltips = true;
boolean urls = true;
// -----------------------------------------------------------
String title = chartDefinition.getTitle();
boolean legend = chartDefinition.isLegendIncluded();
PlotOrientation orientation = chartDefinition.getOrientation();
CategoryAxis categoryAxis = new CategoryAxis(categoryAxisLabel);
ValueAxis valueAxis = new NumberAxis(valueAxisLabel);
BarRenderer renderer = null;
// Determine the type of renderer to use
if (chartDefinition.isStacked() || chartDefinition.isThreeD()) {
if (chartDefinition.isStacked() && chartDefinition.isThreeD()) {
renderer = new StackedBarRenderer3D();
} else if (chartDefinition.isStacked()) {
renderer = new StackedBarRenderer();
} else {
renderer = new BarRenderer3D();
}
} else {
renderer = new BarRenderer();
}
if (orientation == PlotOrientation.HORIZONTAL) {
ItemLabelPosition position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE3, TextAnchor.CENTER_LEFT);
renderer.setPositiveItemLabelPosition(position1);
ItemLabelPosition position2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE9, TextAnchor.CENTER_RIGHT);
renderer.setNegativeItemLabelPosition(position2);
} else if (orientation == PlotOrientation.VERTICAL) {
ItemLabelPosition position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER);
renderer.setPositiveItemLabelPosition(position1);
ItemLabelPosition position2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6, TextAnchor.TOP_CENTER);
renderer.setNegativeItemLabelPosition(position2);
}
if (tooltips) {
renderer.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator());
}
if (urls) {
renderer.setBaseItemURLGenerator(new StandardCategoryURLGenerator());
}
if (chartDefinition.getMaxBarWidth() != null) {
renderer.setMaximumBarWidth(chartDefinition.getMaxBarWidth().doubleValue());
}
CategoryPlot plot = new CategoryPlot(chartDefinition, categoryAxis, valueAxis, renderer);
JFreeChartEngine.updatePlot(plot, chartDefinition);
JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, legend);
return chart;
}Example 69
| Project: pentaho-platform-master File: JFreeChartEngine.java View source code |
private static JFreeChart createBarChart(final CategoryDatasetChartDefinition chartDefinition) {
// TODO Make the following accessible from the chartDefinition
String categoryAxisLabel = null;
String valueAxisLabel = null;
boolean tooltips = true;
boolean urls = true;
// -----------------------------------------------------------
String title = chartDefinition.getTitle();
boolean legend = chartDefinition.isLegendIncluded();
PlotOrientation orientation = chartDefinition.getOrientation();
CategoryAxis categoryAxis = new CategoryAxis(categoryAxisLabel);
ValueAxis valueAxis = new NumberAxis(valueAxisLabel);
BarRenderer renderer = null;
// Determine the type of renderer to use
if (chartDefinition.isStacked() || chartDefinition.isThreeD()) {
if (chartDefinition.isStacked() && chartDefinition.isThreeD()) {
renderer = new StackedBarRenderer3D();
} else if (chartDefinition.isStacked()) {
renderer = new StackedBarRenderer();
} else {
renderer = new BarRenderer3D();
}
} else {
renderer = new BarRenderer();
}
if (orientation == PlotOrientation.HORIZONTAL) {
ItemLabelPosition position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE3, TextAnchor.CENTER_LEFT);
renderer.setPositiveItemLabelPosition(position1);
ItemLabelPosition position2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE9, TextAnchor.CENTER_RIGHT);
renderer.setNegativeItemLabelPosition(position2);
} else if (orientation == PlotOrientation.VERTICAL) {
ItemLabelPosition position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER);
renderer.setPositiveItemLabelPosition(position1);
ItemLabelPosition position2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6, TextAnchor.TOP_CENTER);
renderer.setNegativeItemLabelPosition(position2);
}
if (tooltips) {
renderer.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator());
}
if (urls) {
renderer.setBaseItemURLGenerator(new StandardCategoryURLGenerator());
}
if (chartDefinition.getMaxBarWidth() != null) {
renderer.setMaximumBarWidth(chartDefinition.getMaxBarWidth().doubleValue());
}
CategoryPlot plot = new CategoryPlot(chartDefinition, categoryAxis, valueAxis, renderer);
JFreeChartEngine.updatePlot(plot, chartDefinition);
JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, legend);
return chart;
}Example 70
| Project: openbd-core-master File: cfCHART.java View source code |
/*
* getCategoryPlot
*/
private CategoryPlot getCategoryPlot(List<cfCHARTSERIESData> series, String xAxisTitle, String yAxisTitle, String labelFormat, boolean bShowMarkers, int markerSize, boolean bShow3D, String tipStyle, String drillDownUrl, int xOffset, int yOffset, int yAxisUnits, String seriesPlacement, boolean bSortXAxis, int height, String[] yAxisSymbols, int gridLines) throws cfmRunTimeException {
// Create a category plot
CategoryPlot plot = new CategoryPlot();
// Set the domain axis (the x-axis)
org.jfree.chart.axis.CategoryAxis categoryAxis;
if (bShow3D)
categoryAxis = new CategoryAxis3D(xAxisTitle);
else
categoryAxis = new CategoryAxis(xAxisTitle);
plot.setDomainAxis(categoryAxis);
// Set the range axis (the y-axis)
ValueAxis valueAxis;
DateFormat dateFormat = null;
NumberFormat numberFormat = null;
// Ignore a label format of date if the y-axis is using symbols
if (labelFormat.equals("date") && (yAxisSymbols == null)) {
valueAxis = new DateAxis(yAxisTitle);
dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
((DateAxis) valueAxis).setDateFormatOverride(dateFormat);
} else {
if (yAxisSymbols != null) {
valueAxis = new SymbolAxis(yAxisTitle, yAxisSymbols);
((SymbolAxis) valueAxis).setGridBandsVisible(false);
((SymbolAxis) valueAxis).setAutoRangeStickyZero(true);
} else if (bShow3D) {
valueAxis = new NumberAxis3D(yAxisTitle);
} else {
valueAxis = new NumberAxis(yAxisTitle);
}
if (labelFormat.equals("currency")) {
((NumberAxis) valueAxis).setNumberFormatOverride(NumberFormat.getCurrencyInstance());
numberFormat = NumberFormat.getCurrencyInstance();
} else if (labelFormat.equals("percent")) {
numberFormat = NumberFormat.getPercentInstance();
// without this change .11443
numberFormat.setMaximumFractionDigits(3);
// would be displayed as 11%
// instead of 11.443%
((NumberAxis) valueAxis).setNumberFormatOverride(numberFormat);
} else {
numberFormat = NumberFormat.getInstance();
}
if (yAxisUnits != 0)
((NumberAxis) valueAxis).setTickUnit(new NumberTickUnit(yAxisUnits));
}
plot.setRangeAxis(valueAxis);
// Add a dataset and renderer for each series
int barChartDatasetIndex = -1;
int hBarChartDatasetIndex = -1;
int num = 0;
MinMaxData minMax = new MinMaxData();
for (int i = 0; i < series.size(); i++) {
cfCHARTSERIESData seriesData = series.get(i);
// NOTE: this attribute is only used with category charts.
if (bSortXAxis)
seriesData.sort();
DefaultCategoryDataset dataset;
if ((barChartDatasetIndex != -1) && (seriesData.getType().equals("bar"))) {
dataset = (DefaultCategoryDataset) plot.getDataset(barChartDatasetIndex);
addSeriesDataToDataset(seriesData, dataset, minMax);
// Set the paint style for this series
setPaintStyle(seriesData.getPaintStyle(), plot.getRenderer(barChartDatasetIndex), dataset.getRowCount() - 1, height);
// Add the color list for this series to the custom color renderer
CustomColorRenderer cr = (CustomColorRenderer) plot.getRenderer(barChartDatasetIndex);
cr.addColors(getColorList(seriesData));
continue;
} else if ((hBarChartDatasetIndex != -1) && (seriesData.getType().equals("horizontalbar"))) {
dataset = (DefaultCategoryDataset) plot.getDataset(hBarChartDatasetIndex);
addSeriesDataToDataset(seriesData, dataset, minMax);
// Set the paint style for this series
setPaintStyle(seriesData.getPaintStyle(), plot.getRenderer(hBarChartDatasetIndex), dataset.getRowCount() - 1, height);
// Add the color list for this series to the custom color renderer
CustomColorRenderer cr = (CustomColorRenderer) plot.getRenderer(hBarChartDatasetIndex);
cr.addColors(getColorList(seriesData));
continue;
} else {
dataset = new DefaultCategoryDataset();
addSeriesDataToDataset(seriesData, dataset, minMax);
}
plot.setDataset(num, dataset);
AbstractCategoryItemRenderer renderer = null;
if (seriesData.getType().equals("bar")) {
plot.setOrientation(PlotOrientation.VERTICAL);
renderer = getBarRenderer(seriesPlacement, bShow3D, xOffset, yOffset, getColorList(seriesData));
ItemLabelPosition position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER);
renderer.setPositiveItemLabelPosition(position1);
ItemLabelPosition position2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6, TextAnchor.TOP_CENTER);
renderer.setNegativeItemLabelPosition(position2);
// The margin between items
((BarRenderer) renderer).setItemMargin(0.0);
// in the same category
// The margin between each category
categoryAxis.setCategoryMargin(0.2);
barChartDatasetIndex = num;
} else if (seriesData.getType().equals("horizontalbar")) {
plot.setOrientation(PlotOrientation.HORIZONTAL);
plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
renderer = getBarRenderer(seriesPlacement, bShow3D, xOffset, yOffset, getColorList(seriesData));
if (bShow3D) {
// change rendering order to ensure that bar overlapping is the
// right way around
plot.setRowRenderingOrder(org.jfree.util.SortOrder.DESCENDING);
plot.setColumnRenderingOrder(org.jfree.util.SortOrder.DESCENDING);
}
ItemLabelPosition position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE3, TextAnchor.CENTER_LEFT);
renderer.setPositiveItemLabelPosition(position1);
ItemLabelPosition position2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE9, TextAnchor.CENTER_RIGHT);
renderer.setNegativeItemLabelPosition(position2);
// The margin between items
((BarRenderer) renderer).setItemMargin(0.0);
// in the same category
// The margin between each category
categoryAxis.setCategoryMargin(0.2);
hBarChartDatasetIndex = num;
} else if (seriesData.getType().equals("line")) {
if (bShow3D) {
renderer = new LineRenderer3D();
((LineRenderer3D) renderer).setXOffset(xOffset);
((LineRenderer3D) renderer).setYOffset(yOffset);
} else {
renderer = new LineAndShapeRenderer(true, false);
}
// Enable/Disable displaying of markers
((LineAndShapeRenderer) renderer).setShapesVisible(bShowMarkers);
// Set the shape of the markers based on the markerSize value
((LineAndShapeRenderer) renderer).setShape(getMarker(seriesData.getMarkerStyle(), markerSize));
} else if (seriesData.getType().equals("area")) {
if (seriesPlacement.equals("stacked"))
// this doesn't work for some
renderer = new StackedAreaRenderer();
else
// reason
renderer = new AreaRenderer();
// Truncate the first and last values to match CFMX 7
((AreaRenderer) renderer).setEndType(AreaRendererEndType.TRUNCATE);
categoryAxis.setCategoryMargin(0.0);
} else if (seriesData.getType().equals("step")) {
renderer = new CategoryStepRenderer(true);
} else if (seriesData.getType().equals("scatter")) {
renderer = new LineAndShapeRenderer(false, true);
// Set the shape of the markers based on the markerSize value
((LineAndShapeRenderer) renderer).setShape(getMarker(seriesData.getMarkerStyle(), markerSize));
}
if (!tipStyle.equals("none")) {
if (dateFormat != null)
renderer.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator("({0}, {1}) = {2}", dateFormat));
else
renderer.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator("({0}, {1}) = {2}", numberFormat));
}
if (drillDownUrl != null) {
if (dateFormat != null)
renderer.setBaseItemURLGenerator(new com.newatlanta.bluedragon.CategoryURLGenerator(drillDownUrl, dateFormat));
else
renderer.setBaseItemURLGenerator(new com.newatlanta.bluedragon.CategoryURLGenerator(drillDownUrl, numberFormat));
}
if (seriesData.getSeriesColor() != null)
renderer.setSeriesPaint(0, convertStringToColor(seriesData.getSeriesColor()));
String dataLabelStyle = seriesData.getDataLabelStyle();
if (labelFormat.equals("date")) {
if (dataLabelStyle.equals("none")) {
renderer.setItemLabelsVisible(false);
} else {
setCategoryItemLabelsData(renderer, seriesData);
if (dataLabelStyle.equals("value"))
renderer.setItemLabelGenerator(new CategoryItemLabelGenerator("{2}", dateFormat, yAxisSymbols));
else if (dataLabelStyle.equals("rowlabel"))
renderer.setItemLabelGenerator(new CategoryItemLabelGenerator("{0}", dateFormat, yAxisSymbols));
else if (dataLabelStyle.equals("columnlabel"))
renderer.setItemLabelGenerator(new CategoryItemLabelGenerator("{1}", dateFormat, yAxisSymbols));
else if (dataLabelStyle.equals("pattern"))
renderer.setItemLabelGenerator(new CategoryItemLabelGenerator("{1} {2}", dateFormat, yAxisSymbols));
else
renderer.setItemLabelGenerator(new CategoryItemLabelGenerator(dataLabelStyle, dateFormat, yAxisSymbols));
}
} else {
if (dataLabelStyle.equals("none")) {
renderer.setItemLabelsVisible(false);
} else {
setCategoryItemLabelsData(renderer, seriesData);
if (dataLabelStyle.equals("value"))
renderer.setItemLabelGenerator(new CategoryItemLabelGenerator("{2}", numberFormat, yAxisSymbols));
else if (dataLabelStyle.equals("rowlabel"))
renderer.setItemLabelGenerator(new CategoryItemLabelGenerator("{0}", numberFormat, yAxisSymbols));
else if (dataLabelStyle.equals("columnlabel"))
renderer.setItemLabelGenerator(new CategoryItemLabelGenerator("{1}", numberFormat, yAxisSymbols));
else if (dataLabelStyle.equals("pattern"))
renderer.setItemLabelGenerator(new CategoryItemLabelGenerator("{1} {2} ({3} of {4})", numberFormat, yAxisSymbols));
else
renderer.setItemLabelGenerator(new CategoryItemLabelGenerator(dataLabelStyle, numberFormat, yAxisSymbols));
}
}
// Add the renderer to the plot.
// NOTE: this must be done before the setPaintStyle() call so the
// DrawingSupplier object
// will be set up properly for the generation of default colors.
plot.setRenderer(num, renderer);
// Set the paint style for this series (series 0)
if (seriesData.getType().equals("bar") || seriesData.getType().equals("horizontalbar") || seriesData.getType().equals("area"))
setPaintStyle(seriesData.getPaintStyle(), renderer, 0, height);
num++;
}
// If gridLines was specified then we need to calculate the yAxisUnits
if ((gridLines != -1) && (valueAxis instanceof NumberAxis)) {
// Calculate the yAxisUnits we need to use to create the number of
// gridLines
yAxisUnits = calculateYAxisUnits(gridLines, minMax);
// Set the yAxisUnits
((NumberAxis) valueAxis).setTickUnit(new NumberTickUnit(yAxisUnits));
}
return plot;
}Example 71
| Project: openaltimeter-downloader-master File: AltimeterAnnotationManager.java View source code |
private XYHeightAnnotation addHeightAnnotationIntenal(double time, double heightInPlotUnits, Paint color) {
XYHeightAnnotation annotation = new XYHeightAnnotation(String.format("%.1f", heightInPlotUnits), time, heightInPlotUnits, color);
annotation.setTextAnchor(TextAnchor.BOTTOM_CENTER);
cp.getChart().getXYPlot().addAnnotation(annotation);
return annotation;
}