Area chart in JFreeChart includes zero - jfreechart

Here is how my area chart in JFreeChart looks like. The area chart starts from 0 and rises up to the first value 5 or 1. Also after 400 on the y axis it falls down back to zero. I want it to start from 5 or 1 and not fall back to 0 after 400.
Area Chart http://imageshack.com/a/img837/6572/2ab0.jpg
Given below is the code. How do I fix it to avoid the zero?
package com.ebay.aerohc.benchmark;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.RefineryUtilities;
import org.jfree.ui.VerticalAlignment;
import org.jfree.util.Log;
import org.jfree.util.PrintStreamLogTarget;
/**
* A simple demonstration application showing how to create an area chart using data from a
* {#link CategoryDataset}.
*/
public class AreaChartDemo extends ApplicationFrame {
/**
* Creates a new demo application.
*
* #param title the frame title.
*/
public AreaChartDemo(final String title) {
super(title);
// create a dataset...
final double[][] data = new double[][] {
{1.0, 4.0, 3.0, 5.0, 5.0, 7.0, 7.0, 8.0},
{5.0, 7.0, 6.0, 8.0, 4.0, 4.0, 2.0, 1.0}/*,
{4.0, 3.0, 2.0, 3.0, 6.0, 3.0, 4.0, 3.0}*/
};
final CategoryDataset dataset = DatasetUtilities.createCategoryDataset(
new String[]{"AeroHC","KernelAHC"}, new String[]{"50","100","150","200","250","300","350","400"}, data
);
// create the chart...
final JFreeChart chart = createChart(dataset);
final ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new Dimension(500, 270));
chartPanel.setEnforceFileExtensions(false);
setContentPane(chartPanel);
}
// ****************************************************************************
// * JFREECHART DEVELOPER GUIDE *
// * The JFreeChart Developer Guide, written by David Gilbert, is available *
// * to purchase from Object Refinery Limited: *
// * *
// * http://www.object-refinery.com/jfreechart/guide.html *
// * *
// * Sales are used to provide funding for the JFreeChart project - please *
// * support us so that we can continue developing free software. *
// ****************************************************************************
/**
* Creates a chart.
*
* #param dataset the dataset.
*
* #return The chart.
*/
private JFreeChart createChart(final CategoryDataset dataset) {
final JFreeChart chart = ChartFactory.createAreaChart(
"Area Chart", // chart title
"Category", // domain axis label
"Value", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
true, // include legend
true, // tooltips
false // urls
);
// NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
// set the background color for the chart...
// final StandardLegend legend = (StandardLegend) chart.getLegend();
// legend.setAnchor(StandardLegend.SOUTH);
chart.setBackgroundPaint(Color.white);
final TextTitle subtitle = new TextTitle("An area chart demonstration. We use this "
+ "subtitle as an example of what happens when you get a really long title or "
+ "subtitle.");
subtitle.setFont(new Font("SansSerif", Font.PLAIN, 12));
subtitle.setPosition(RectangleEdge.TOP);
// subtitle.setSpacer(new Spacer(Spacer.RELATIVE, 0.05, 0.05, 0.05, 0.05));
subtitle.setVerticalAlignment(VerticalAlignment.BOTTOM);
chart.addSubtitle(subtitle);
final CategoryPlot plot = chart.getCategoryPlot();
plot.setForegroundAlpha(0.5f);
// plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
plot.setBackgroundPaint(Color.lightGray);
plot.setDomainGridlinesVisible(true);
plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.white);
final CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
domainAxis.setLowerMargin(0.1);
domainAxis.setUpperMargin(0.5);
domainAxis.addCategoryLabelToolTip("Type 1", "The first type.");
domainAxis.addCategoryLabelToolTip("Type 2", "The second type.");
domainAxis.addCategoryLabelToolTip("Type 3", "The third type.");
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
rangeAxis.setLabelAngle(0 * Math.PI / 2.0);
rangeAxis.setAutoRangeIncludesZero(false);
// OPTIONAL CUSTOMISATION COMPLETED.
return chart;
}
/**
* Starting point for the demonstration application.
*
* #param args ignored.
*/
public static void main(final String[] args) {
Log.getInstance().addTarget(new PrintStreamLogTarget());
final AreaChartDemo demo = new AreaChartDemo("Area Chart Demo");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
}

You can configure this in the renderer:
AreaRenderer renderer = (AreaRenderer) plot.getRenderer();
renderer.setEndType(AreaRendererEndType.LEVEL);

Use an XYSeriesCollection for your dataset and switch to using ChartFactory#createXYAreaChart.
You will need to change some of the configuration as you will not be using a CategoryAxis

Not enough rep to comment on David Gilbert's answer, so I have to post a separate answer.
I had the desired results when configuring the truncate end type in the renderer:
AreaRenderer renderer = (AreaRenderer) plot.getRenderer();
renderer.setEndType(AreaRendererEndType.TRUNCATE);

Related

Babylon js texture issue when used with reactjs

I'm implementing 3D demo application using Babylonjs library for 3D Demo.I'm importing 3D model from S3 and adding texture image on top of material in Reactjs.
But when i add texture image on top of material, rest of area on 3D model gets black color and i want get rid of it. Code works fine in Babylon playground but fails in React app.
Here is the source code
var mat = new BABYLON.CustomMaterial("mat", scene);
mat.diffuseTexture = new BABYLON.Texture(textureImage, scene, false, false);
materialedMeshes.forEach(mesh => mesh.material = mat);
mat.emissiveColor = new BABYLON.Color3(1, 1, 1);
// mat.diffuseColor = new BABYLON.Color3(1, 0, 1);
// mat.specularColor = new BABYLON.Color3(0.5, 0.6, 0.87);
// mat.emissiveColor = new BABYLON.Color3(1, 1, 1);
// mat.ambientColor = new BABYLON.Color3(0.23, 0.98, 0.53);
mat.diffuseTexture.uOffset = -0.1000;
mat.diffuseTexture.vOffset = -1.1800;
mat.diffuseTexture.uScale = 1.2200;
mat.diffuseTexture.vScale = 2.2200;
mat.diffuseTexture.uAng = Math.PI;
mat.diffuseTexture.wrapU = BABYLON.Constants.TEXTURE_CLAMP_ADDRESSMODE;
mat.diffuseTexture.wrapV = BABYLON.Constants.TEXTURE_CLAMP_ADDRESSMODE;
mat.Fragment_Custom_Alpha(`
if (baseColor.r == 0. && baseColor.g == 0. && baseColor.b == 0.) {
baseColor.rgb = vec3(0.85, 0.85, 0.85);
}
baseColor.rgb = mix(vec3(0.85, 0.85, 0.85), baseColor.rgb, baseColor.a);
`)

EncodedImage failing to work on actual phone

I am facing a problem while using encodedImage. When a user logins into the app, the first form after successful login has an image. And the image is causing me issues upon retrieving it.
When the user captures an image in the app, I convert it to a base64 string which I send to the server. The code for that is:
ImageIO img = ImageIO.getImageIO();
ByteArrayOutputStream out = new ByteArrayOutputStream();
img.save(et, out, ImageIO.FORMAT_JPEG, 1);
byte[] ba = out.toByteArray();
String userImage64 = Base64.encodeNoNewline(ba);
et is the captured image. So I store the string userImage64 in the server.
When I retrieve the base64, I decode it and convert it to an EncodedImage. The code is:
String url = new JSONObject(result.getResponseData()).getString("photo");
byte[] b = Base64.decode(url.getBytes());
Image icon = EncodedImage.create(b);
When I am on the simulator, everything flows smoothly. The images display and everything works very well.
My issue is, when I put the app on an android device, it doesn't work. It shows me a toast of successful login and just stops there. So i did some debugging and realized that issue is with the three lines of converting from base64 to image. When I comment out the three lines, everything works very well. Where could I be going wrong?
EDIT
Below is the code I use to capture a photo:
String i = Capture.capturePhoto();
if (i != null) {
try {
final Image newImage = Image.createImage(i);
Image roundedMask = Image.createImage(rich.minScreensize() / 4, rich.minScreensize() / 4, 0xff000000);
Graphics gra = roundedMask.getGraphics();
gra.setColor(0xffffff);
gra.fillArc(0, 0, rich.minScreensize() / 4, rich.minScreensize() / 4, 0, 360);
Object masked = roundedMask.createMask();
cropImage(newImage, rich.minScreensize() / 4, rich.minScreensize() / 4, et -> {
if (editing) {
try {
ImageIO img = ImageIO.getImageIO();
ByteArrayOutputStream out = new ByteArrayOutputStream();
img.save(et, out, ImageIO.FORMAT_JPEG, 1);
byte[] ba = out.toByteArray();
userImage64 = Base64.encodeNoNewline(ba);
et = et.applyMask(masked);
logoimage.setIcon(et);
///removed unnecessary code
logoimage.getComponentForm().revalidate();
} catch (IOException ex) {
}
} else {
et = et.applyMask(masked);
logoimage.setIcon(et);
}
});
} catch (IOException ex) {
Log.p("Error loading captured image from camera", Log.ERROR);
}
}
Inside there is code I use to crop the photo and that is code is:
private void cropImage(Image img, int destWidth, int destHeight, OnComplete<Image> s) {
Form previous = getCurrentForm();
Form cropForm = new Form("", new LayeredLayout());
Label toobarLabel = new Label("New Holder", "Toolbar-HeaderLabel");
cropForm.setTitleComponent(toobarLabel);
Toolbar mainToolbar = new Toolbar();
mainToolbar.setUIID("ToolBar");
cropForm.setToolbar(mainToolbar);
Label moveAndZoom = new Label("Move and zoom the photo to crop it");
moveAndZoom.getUnselectedStyle().setFgColor(0xffffff);
moveAndZoom.getUnselectedStyle().setAlignment(CENTER);
moveAndZoom.setCellRenderer(true);
cropForm.setGlassPane((Graphics g, Rectangle rect) -> {
g.setColor(0x0000ff);
g.setAlpha(150);
Container cropCp = cropForm.getContentPane();
int posY = cropForm.getContentPane().getAbsoluteY();
GeneralPath p = new GeneralPath();
p.setRect(new Rectangle(0, posY, cropCp.getWidth(), cropCp.getHeight()), null);
if (isPortrait()) {
p.arc(0, posY + cropCp.getHeight() / 2 - cropCp.getWidth() / 2,
cropCp.getWidth() - 1, cropCp.getWidth() - 1, 0, Math.PI * 2);
} else {
p.arc(cropCp.getWidth() / 2 - cropCp.getHeight() / 2, posY,
cropCp.getHeight() - 1, cropCp.getHeight() - 1, 0, Math.PI * 2);
}
g.fillShape(p);
g.setAlpha(255);
g.setColor(0xffffff);
moveAndZoom.setX(0);
moveAndZoom.setY(posY);
moveAndZoom.setWidth(cropCp.getWidth());
moveAndZoom.setHeight(moveAndZoom.getPreferredH());
moveAndZoom.paint(g);
});
final ImageViewer viewer = new ImageViewer();
viewer.setImage(img);
cropForm.add(viewer);
cropForm.getToolbar().addMaterialCommandToRightBar("", FontImage.MATERIAL_CROP, e -> {
previous.showBack();
s.completed(viewer.getCroppedImage(0).
fill(destWidth, destHeight));
});
cropForm.getToolbar().addMaterialCommandToLeftBar("", FontImage.MATERIAL_CANCEL, e -> previous.showBack());
cropForm.show();
}

Add text to picture in Windows Universal app

I have universal app created for Win 10 mobile which captures photo. I want to add stamp (some text) to my photo. Is it possible? It seems working with bitmap is really difficult in universal applications
Check this link:
How to add wartermark text/image to a bitmap in Windows Store app
Or better use Win2D library (you can find it on NuGet) and snippet like this:
CanvasDevice device = CanvasDevice.GetSharedDevice();
CanvasRenderTarget offscreen = new CanvasRenderTarget(device, 500, 500, 96);
cbi = await CanvasBitmap.LoadAsync(device, "mydog.jpg");
using (var ds = offscreen.CreateDrawingSession())
{
ds.DrawImage(cbi);
var format = new CanvasTextFormat()
{
FontSize = 24,
HorizontalAlignment = CanvasHorizontalAlignment.Left,
VerticalAlignment = CanvasVerticalAlignment.Top,
WordWrapping = CanvasWordWrapping.Wrap,
FontFamily = "Tahoma"
};
var tl = new CanvasTextLayout(ds, "Some text", format, 200, 50); // width 200 and height 50
ds.DrawTextLayout(tl, 10, 10, Colors.Black);
tl.Dispose();
}
using (var stream = new InMemoryRandomAccessStream())
{
stream.Seek(0);
await offscreen.SaveAsync(stream, CanvasBitmapFileFormat.Png);
BitmapImage image = new BitmapImage();
image.SetSource(stream);
img.Source = image;
}

Re textArea growByLimit issues in layerLayout

I set the textArea setGrowByContent true and setGrowLimit to 2, but there is always only one row. So i twisted the code and increase the
height of textArea by twice if the size of textArea is greater than Button size. Below is the codes. My issue is at the end of the question:
Button homeButtonn = new Button(btnIcon){
#Override
protected Dimension calcPreferredSize() {
System.out.println("Button size: " + super.calcPreferredSize());
return super.calcPreferredSize();
}
#Override
public void setUIID(String id) {
super.setUIID("homeButtonn");
}
};
TextArea buttonTitle = new TextArea(title){
#Override
protected Dimension calcPreferredSize() {
System.out.println("textArea title: " + getText());
System.out.println("Textarea size: " +super.calcPreferredSize());
System.out.println("");
return super.calcPreferredSize();
}
};
buttonTitle.setUIID("smallLabel");
buttonTitle.getAllStyles().setAlignment(Label.LEFT);
zeroPaddingMargin(buttonTitle);
if (buttonTitle.getPreferredW() -10 > homeButtonn.getPreferredW()) {
buttonTitle.setPreferredH(buttonTitle.getPreferredH() * 2);
}
buttonTitle.setPreferredW(homeButtonn.getPreferredW() - 10);
buttonTitle.getAllStyles().setMargin(3, 3, 3, 3);
buttonTitle.setEditable(false);
buttonTitle.setGrowByContent(true);
buttonTitle.setGrowLimit(2);
buttonTitle.setScrollVisible(false);
gridContainer.add(LayeredLayout.encloseIn(homeButtonn, FlowLayout.encloseRightBottom(buttonTitle)));
OUTPUT:
Button size: width = 146 height = 140
textArea title: DJ and Sound
Textarea size: width = 194 height = 25
Here textArea size is greater than button size but if i set size of the textArea with exact size of button,
it fits well. So how can textArea size be greater than button size and also all texts of textArea fits well inside button?
The problem i got is that since textArea size is greater than button size, the height of textArea is multiplied by twice its own height but
textArea fit well in single line and it leaves extra line/row below.
PS see the screenshot. Thankyou
without calcPreferred size or preferredSize:
If calcPreferredSize is removed, it takes whole screenwidth though it is in gridlayout with 3 column
Update:
Recent Code without calcPreferredSize & textArea nested in a container too
GridLayout gl2 = new GridLayout(counter / 3 + 1, 3);
gl2.setAutoFit(true);
Container gridContainer = new Container(gl2);
gridContainer.setScrollableY(true);
f.addComponent(gridContainer);
imageUrl = entry.get("img").toString();
title = entry.get("name").toString();
homePlaceholder = homePlaceholder.scaled(screenWidth / 3 - 20, screenWidth / 3 - 26);
encodedHomePlaceholder = EncodedImage.createFromImage(homePlaceholder, true);
Image btnIcon = URLImage.createToStorage(encodedHomePlaceholder, "home_" + title + imageUrl, allUrl.globalHomeImageUrl + imageUrl, URLImage.RESIZE_SCALE_TO_FILL);
homeButton.setIcon(btnIcon);
TextArea buttonTitle = new TextArea(title);
buttonTitle.getAllStyles().setAlignment(Label.LEFT);
buttonTitle.getAllStyles().setMargin(3, 3, 3, 3);
buttonTitle.setEditable(false);
buttonTitle.setGrowByContent(true);
buttonTitle.setGrowLimit(2);
buttonTitle.setScrollVisible(false);
Container btnTitleContainer = new Container();
btnTitleContainer.addComponent(buttonTitle);
gridContainer.add(LayeredLayout.encloseIn(homeButton, FlowLayout.encloseRightBottom(btnTitleContainer)));
f.revalidate();
Don't use calcPreferredSize, setPreferred* or any such API when you want something to be automatically calculated.
By definition you are disabling the automatic calculation when you are using these APIs that is why most of those API's are deprecated.
You need to only use layout logic.
What ever i did to make it right in layer layout and textarea, it didnt work so i tried other things and it work. I set the bg image of the container with border layout & keep the textarea in the south of borderlayout.
homePlaceholder = homePlaceholder.scaled(screenWidth / 3, screenWidth / 3);
encodedHomePlaceholder = EncodedImage.createFromImage(homePlaceholder, true);
Image btnIcon = URLImage.createToStorage(encodedHomePlaceholder, "home_" + title + imageUrl, allUrl.globalHomeImageUrl + imageUrl, URLImage.RESIZE_SCALE_TO_FILL);
Container innerContainer = new Container(new BorderLayout());
innerContainer.getAllStyles().setBgImage(btnIcon);
innerContainer.getAllStyles().setBackgroundType(Style.BACKGROUND_IMAGE_SCALED);
gridContainer.add(innerContainer);
TextArea buttonTitle = new TextArea(properCase(title));
buttonTitle.setUIID("smallLabel");
zeroPaddingMargin(buttonTitle);
innerContainer.add(BorderLayout.SOUTH,buttonTitle);
buttonTitle.setEditable(false);
buttonTitle.setGrowByContent(true);
buttonTitle.setGrowLimit(2);
buttonTitle.setScrollVisible(false);
gridContainer.revalidate();

how to dissable x-axis line in jfreecharts

Im using jfreecharts for my application. I need to remove the x-axis line in the Line chart produced. How can i remove the axis line, Any help would be appreciated.
To remove your axis line and tick marks, refer this code.
final DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(1.0, "Line", "2009");
dataset.addValue(2.0, "Line", "2010");
dataset.addValue(null, "Line", "2011");
dataset.addValue(3.0, "Line", "2012");
final JFreeChart chart = ChartFactory.createLineChart(
"", // chart title
"", // domain axis label
"", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
false, // include legend
false, // tooltips
false // urls
);
chart.setBackgroundPaint(Color.WHITE);
final CategoryPlot plot = (CategoryPlot) chart.getPlot();
plot.setBackgroundPaint(Color.WHITE);
plot.setRangeZeroBaselinePaint(Color.RED);
plot.setOutlineVisible(false);
plot.setRangeGridlinePaint(Color.white);
plot.setDomainGridlinePaint(Color.BLUE);
final CategoryAxis categoryAxis = (CategoryAxis) plot.getDomainAxis();
categoryAxis.setAxisLineVisible(false);
categoryAxis.setTickMarksVisible(false);
//categoryAxis.setVisible(false);
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
//rangeAxis.setAxisLineVisible(false);
rangeAxis.setVisible(false);
rangeAxis.setLabelPaint(Color.BLUE);
rangeAxis.setRange(0, 3);
final LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
//renderer.setItemLabelsVisible(false); //Deprecated.
renderer.setBaseShapesVisible(true);
renderer.setBaseShapesFilled(true);
renderer.setSeriesStroke(0, new BasicStroke(2.0f));
Shape circle = new Ellipse2D.Double(-3, -3, 6, 6);
renderer.setSeriesShape(0, circle);
plot.getRenderer().setSeriesPaint(0, Color.BLUE);
try {
ChartUtilities.saveChartAsPNG(new File("E:\\jfreeLinechart.png"), chart, 211, 90);
System.out.println("=====chart=====");
} catch (Exception e) {
e.printStackTrace();
}
Also refer this link

Resources