I have 2 Achartengine XYSeries problems - eclipse

I’m having 2 problems with a simple XYSeries line graph.
When the absolute value of the difference between the last plotted point and the next plotted point is less than 11 the label on the next plotted point goes missing. I want all the labels to display.
I have some (not all) missing vertical grid lines and don’t see why. I want a vertical grid line for every XY coordinate.
Thanks for the help. Here's the code.
String glucoseLegendText = getString(R.string.glucose_legend_text);
XYSeries series = new XYSeries(glucoseLegendText);
datasource = new HistoryDataSource(this);
datasource.open();
Cursor c = datasource.getQuery();
c.moveToFirst();
int cnt = c.getCount();
int minValue = 0;
int maxValue = 0;
for (int i = 0; i < cnt; i++) {
int glucoseValue = c.getInt(2);
series.add(i, glucoseValue);
if (i == 0 || glucoseValue < minValue)
minValue = glucoseValue;
if (glucoseValue > maxValue)
maxValue = glucoseValue;
c.moveToNext();
}
datasource.close();
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
dataset.addSeries(series);
XYSeriesRenderer renderer = new XYSeriesRenderer();
renderer.setColor(Color.BLUE);
renderer.setPointStyle(PointStyle.CIRCLE);
renderer.setFillPoints(true);
renderer.setLineWidth(3);
renderer.setDisplayChartValues(true);
renderer.setChartValuesTextSize(15);
renderer.setChartValuesTextAlign(Align.LEFT);
XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
mRenderer.addSeriesRenderer(renderer);
mRenderer.setShowGrid(true);
mRenderer.setGridColor(Color.BLACK);
mRenderer.setXLabels(cnt); // to control number of grid lines
mRenderer.setYLabels(cnt); // to control number of grid lines
mRenderer.setXLabelsColor(Color.YELLOW);
mRenderer.setPointSize(5);
mRenderer.setYLabelsAlign(Align.RIGHT);
mRenderer.setLegendTextSize(15);
mRenderer.setZoomButtonsVisible(true);
mRenderer.setYAxisMin(minValue - 2); // buffer bottom
mRenderer.setYAxisMax(maxValue + 3); // buffer top
// Populate the X labels with the dates and times
c.moveToFirst();
for (int d = 0; d < cnt; d++) {
timeStamp = c.getString(1);
date = timeStamp.substring(0, 5);
time = timeStamp.substring(9, 14);
if (date.equals(dateLast)) {
mRenderer.addXTextLabel(d, "\n" + time);
} else
mRenderer.addXTextLabel(d, "\n" + time + "\n" + date);
dateLast = date;
c.moveToNext();
}
c.close();
GraphicalView gview = ChartFactory.getTimeChartView(this, dataset,
mRenderer, "");
LinearLayout layout = (LinearLayout) findViewById(R.id.Chart);
layout.addView(gview);

For the first question, you can control the labels display using
renderer.setXLabels(approximateNumberOfLabels);
For the second question, the grid lines are displayed along the labels.

Related

How to plot a histogram with strings in anylogic

i have an array with some random sequence
for example : long[] X = {23,1,4,2,.............,4,2,1,3,..........};
in data base i have the names for each numbers(names in the image)
i want to plot a histogram for (23,4);(1,2);(4,2);(2,3)............from the sequence in X[].
but I need something like this
I am not sure how to do it, as the data set only allows the type double, how can I add strings.
long[] X = Disassemblysequence.getDisassemblySequence(); //random sequence
String[] Components = f_Components(); //list of Components from data base
for(int i = 0; i<C; i++){
String A = Components[(int)(X[i] -1)];
double EOL = (double)X[i+C];
String Status = "";
//double Com = (double) X[i];
//double S = (double) X[i+C];
if (EOL == 0){
Status = "Not Removed";
}
else if(EOL == 2){
Status = "Reuse";
}
else if(EOL == 3){
Status = "Remanufacture";
}
else if(EOL == 4){
Status = "Recycle";
}
d_Components.add(A,EOL);
}
It appears that you don't want a histogram per see, since a histogram will calculate some of the values for you, which you already have calculated. Rather you simply need to display them in a bar chart.
You can add bars to a bar chart using standard code see example below
And here is the output
If you want to have custom x-axis labels you need to not show the legend and create your own - but this can be a separate question

How to select and drag an ellipse in old version of Processing?

//The following game has been designed as an educational resource
//for Key Stage 1 and 2 children. Children are the future of
//civil engineering, and to inspire them to get involved in the
//industry is important for innovation. However, today the
//national curriculum is very structured, and many children
//can find themselves falling behind even at the age of 7 or 8.
//It is essential that children can be supported with material
//they find difficult, and given the resources to learn in a
//fun and engaging manner.
//One of the topics that many children struggle to grasp is
//fractions. It is necessary to prevent young children feeling
//like STEM subjects are too difficult for them, so that they
//have the opportunity and confidence to explore science and
//engineering subjects as they move into secondary education and
//careers.
//This game intends to set a precedent for teaching complex
//subjects to children in a simple, but fun and interactive
//manner. It will show them that fractions can be fun, and that
//they are capable, building confidence once they return to
//the classroom.
//The game will work by challenging the user to split a group
//of balls into three buckets depending on the fraction
//displayed on the bucket.
int number_of_balls;
float bucket_1, bucket_2, bucket_3;
int bucket_1_correct, bucket_2_correct, bucket_3_correct;
PVector basket_position, basket_dimensions;
Ball[] array_of_balls;
int linethickness;
//Random generator to give number of balls, ensuring that
//they can be divided into the number of buckets available.
void setup()
{
size(500,500);
linethickness = 4;
number_of_balls = int(random(1,11))*6;
println(number_of_balls);
bucket_1 = 1/6;
bucket_2 = 1/2;
bucket_3 = 1/3;
//Working out the correct answers
bucket_1_correct = number_of_balls*bucket_1;
bucket_2_correct = number_of_balls*bucket_2;
bucket_3_correct = number_of_balls*bucket_3;
println (bucket_1, bucket_2, bucket_3);
println (bucket_1_correct, bucket_2_correct, bucket_3_correct);
//Creating the basket
basket_position = new PVector(width/4, height/8);
basket_dimensions = new PVector(width/2, height/4);
//Creating the balls & placing inside basket
array_of_balls = new Ball[number_of_balls];
for (int index=0; index<number_of_balls; index++)
{
array_of_balls[index] = new Ball();
}
}
//Drawing the balls and basket outline
void draw()
{
background (125,95,225);
for (int index=0; index<number_of_balls; index++)
{
array_of_balls[index].Draw();
}
noFill();
stroke(180,0,0);
strokeWeight(linethickness);
rect(basket_position.x, basket_position.y, basket_dimensions.x, basket_dimensions.y);
}
void mouseDragged()
{
if ((mouseX >= (ball_position.x - radius)) && (mouseX <= (ball_position.x + radius)) && (mouseY >= (ball_position.y - radius)) && (mouseY <= (ball_position.y + radius)))
{
ball_position = new PVector (mouseX, mouseY);
}
}
//Ball_class
int radius;
Ball()
{
radius = 10;
ball_position = new PVector (random(basket_position.x + radius + linethickness, basket_position.x + basket_dimensions.x - radius - linethickness), random(basket_position.y + radius + linethickness, basket_position.y + basket_dimensions.y - radius - linethickness));
colour = color(random(255), random(255), random(255));
}
void Draw()
{
noStroke();
fill(colour);
ellipse(ball_position.x,ball_position.y,radius*2,radius*2);
}
}
Thanks in advance for your help! I am using Processing 2.2.1 which I know is very out of date, so struggling to find help.
I have a piece of code that has created a number of balls, and I would like to be able to 'drag and drop' these to a different location on the screen as part of an educational game. I've tried playing around with mousePressed() and mouseDragged() but no luck yet. Any advice would be appreciated!
There are a lot of ways to approach this, but one way I could suggest is doing something like this:
// "Ellipse" object
function Ellipse (x, y, width, height) {
// Each Ellipse object has their own x, y, width, height, and "selected" values
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.selected = false;
// You can call the draw function whenever you want something done with the object
this.draw = function() {
// Draw ellipse
ellipse(this.x, this.y, this.width, this.height);
// Check if mouse is touching the ellipse using math
// https://www.desmos.com/calculator/7a9u1bpfvt
var xDistance = this.x - mouseX;
var yDistance = this.y - mouseY;
// Ellipse formula: (x^2)/a + (y^2)/b = r^2
// Assuming r = 1 and y = 0:
// 0 + (x^2)/a = 1 Substitute values
// ((width / 2)^2)/a = 1 x = width / 2 when y = 0
// a = (width / 2)^2 Move numbers around
// a = (width^2) / 4 Evaluate
var a = Math.pow(this.width, 2) / 4;
// Assuming r = 1 and x = 0:
// 0 + (y^2)/b = 1 Substitute values
// ((height / 2)^2)/b = 1 y = height / 2 when x = 0
// b = (height / 2)^2 Move numbers around
// b = (height^2) / 4 Evaluate
var b = Math.pow(this.height, 2) / 4;
// x^2
var x2 = Math.pow(xDistance, 2);
// y^2
var y2 = Math.pow(yDistance, 2);
// Check if coordinate is inside ellipse and mouse is pressed
if(x2 / a + y2 / b < 1 && mouseIsPressed) {
this.selected = true;
}
// If mouse is released, deselect the ellipse
if(!mouseIsPressed) {
this.selected = false;
}
// If selected, then move the ellipse
if(this.selected) {
// Moves ellipse with mouse
this.x += mouseX - pmouseX;
this.y += mouseY - pmouseY;
}
};
}
// New Ellipse object
var test = new Ellipse(100, 100, 90, 60);
draw = function() {
background(255);
// Do everything associated with that object
test.draw();
};
The math is a bit funky, and I might not be using the right version of Processing, but hopefully you found this at least slightly helpful :)
I'm kind of confused about what language you're using. Processing is a wrapper for Java, not JavaScript. Processing.js went up to version 1.6.6 and then was succeeded by p5.js. I'm going to assume you're using p5.js.
I don't know if this is a new thing in p5.js, but for easy, but not very user-friendly click-and-drag functionality I like to use the built-in variable mouseIsPressed.
If the ellipse coordinates are stored in an array of vectors, you might do something like this:
let balls = [];
let radius = 10;
function setup() {
createCanvas(400, 400);
for (let i = 0; i < 10; i++) {
balls.push(createVector(random(width), random(height)));
}
}
function draw() {
background(220);
for (let i = 0; i < balls.length && mouseIsPressed; i++) {
if (dist(mouseX, mouseY, balls[i].x, balls[i].y) < radius) {
balls[i] = createVector(mouseX, mouseY);
i = balls.length;
}
}
for (let i = 0; i < balls.length; i++) {
ellipse(balls[i].x, balls[i].y,
2 * radius, 2 * radius
);
}
}
This is the quickest way I could think of, but there are better ways to do it (at least, there are in p5.js). You could make a Ball class which has numbers for x, y, and radius, as well as a boolean for whether it's being dragged. In that class, you could make a method mouseOn() which detects whether the cursor is within the radius (if it's not a circle, you can use two radii: sq((this.x - mouseX)/r1) + sq((this.y - mouseY)/r2) < 1).
When the mouse is pressed, you can cycle through all the balls in the array of balls, and test each of them with mouseOn(), and set their drag boolean to true. When the mouse is released, you can set all of their drag booleans to false. Here's what it looks like in the current version of p5.js:
function mousePressed() {
for (let i = 0; i < balls.length; i++) {
balls[i].drag = balls[i].mouseOn();
if (balls[i].drag) {
i = balls.length;
}
}
}
function mouseReleased() {
for (let i = 0; i < balls.length; i++) {
balls[i].drag = false;
}
}
I hope this helps.
The way your code is right now doesn't work in the current version of Processing either, but it's a pretty quick fix. I'm going to show you a way to fix that, and hopefully it'll work in the earlier version.
Here's where I think the problem is: when you use mouseDragged(), you try to change ball_position, but you don't specify which ball's position. Here's one solution, changing the mouseDragged() block and the Ball class:
void mouseDragged() {
for (int i = 0; i < array_of_balls.length; i++) {
if ((mouseX > (array_of_balls[i].ball_position.x - array_of_balls[i].radius)) &&
(mouseX < (array_of_balls[i].ball_position.x + array_of_balls[i].radius)) &&
(mouseY > (array_of_balls[i].ball_position.y - array_of_balls[i].radius)) &&
(mouseY < (array_of_balls[i].ball_position.y + array_of_balls[i].radius))
) {
array_of_balls[i].ball_position = new PVector (mouseX, mouseY);
i = array_of_balls.length;
}
}
}
//Ball_class
class Ball {
int radius;
PVector ball_position;
color colour;
Ball() {
radius = 10;
ball_position = new PVector (random(basket_position.x + radius + linethickness, basket_position.x + basket_dimensions.x - radius - linethickness), random(basket_position.y + radius + linethickness, basket_position.y + basket_dimensions.y - radius - linethickness));
colour = color(random(255), random(255), random(255));
}
void Draw() {
noStroke();
fill(colour);
ellipse(ball_position.x, ball_position.y, radius*2, radius*2);
}
}
P.S. Since you're using a language based in Java, you should probably adhere to the finnicky parts of the language:
data types are very strict in Java. Avoid assigning anything that could possibly be a float to a variable that is declared as an int. For example, in your setup() block, you say bucket_1_correct = number_of_balls*bucket_1;. This might seem like not an issue, since number_of_balls*bucket_1 is always going to be a whole number. But since the computer rounds when saving bucket_1 = 1/6, multiplying it by 6 doesn't necessarily give a whole number. In this case, you can just use round(): bucket_1_correct = round(number_of_balls*bucket_1);
Regarding data types, you should always declare your variables with their data type. It's a little hard for me to tell, but it looks to me like you never declared ball_position or colour in your Ball class, and you never opened up the class with the typical class Ball {. This might have been a copy/paste error, though.

min and max value for date axis in amcharts4

I have a line graph with date axis and data being displayed in intervals for 30 or 15 minutes for a day. Since data is dynamic, for some cases data starts around 12 noon or some other time and hence the x-axis does not always starts from the 00:00. Similarly data might end before 12:00 Mid night.
I want to always show the dateAxis to start from 00:00 then some fix step for lets say a label for every one or two hours and end at 12:00 mid night. How can i do this?
I tried DateAxis.min and DateAxis.max. But these are only accepting numeric values. not sure how to set it to appropriate numeric value to represent the start and end of day.
I also tried setting DateAxis.extraMin and DateAxis.extraMax but these are working on percentage and its a but hard to find appropriate values for the dynamic data.
This is how current graph renders
This is how i want to display (notice the empty labels at the start)
The min/max properties in DateAxis objects take millisecond timestamps. You can use the result of getTime() from a JavaScript Date object:
dateAxis.min = (new Date(2019,7,10)).getTime();
dateAxis.max = (new Date(2019,7,10,23)).getTime();
There isn't a way to explicitly set a step, though. You can tweak minGridDistance to influence the step but that's about it. The only workaround you can use is insert guides (Axis Ranges) at each timestamp with the appropriate label and disable the DateAxis' default labels.
range.date = new Date(2019, 7, 10, 0);
range.grid.strokeOpacity = .5;
range.grid.stroke = "#cecece";
range.label.text = "00:00";
Note that axis won't adjust label visibility in this case, so you may need to set a rotation on the range label as well.
Demo below:
// Create chart instance
var chart = am4core.create("chartdiv", am4charts.XYChart);
// Add data
chart.data = generateData();
// Create axes
var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.startLocation = 0.5;
dateAxis.endLocation = 0.5;
// Create value axis
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
// Create series
var series = chart.series.push(new am4charts.LineSeries());
series.dataFields.valueY = "value";
series.dataFields.dateX = "date";
series.name = "Sales";
series.strokeWidth = 3;
series.fillOpacity = 0.5;
dateAxis.baseInterval = {
timeUnit: "minute",
count: 15
}
dateAxis.renderer.grid.template.disabled = true;
dateAxis.renderer.labels.template.disabled = true;
dateAxis.min = (new Date(2019, 7, 10, 0)).getTime();
dateAxis.max = (new Date(2019, 7, 10, 23)).getTime();
generateRanges(dateAxis);
function generateRanges(axis) {
var firstDate = new Date(2019, 7, 10, 0);
for (var i = 0; i < 24; ++i) {
var range = axis.axisRanges.create();
var nextDate = new Date(firstDate);
nextDate.setHours(i);
range.date = nextDate;
range.grid.strokeOpacity = .5;
range.grid.stroke = "#cecece";
range.label.text = ("0" + nextDate.getHours()).substr(-2) + ":" + ("0" + nextDate.getMinutes()).substr(-2);
range.label.rotation = 90;
}
}
function generateData() {
var data = [];
var firstDate = new Date(2019, 7, 10, 10);
for (var i = 0; i < 32; ++i) {
var nextDate = new Date(firstDate);
nextDate.setMinutes(i * 15);
data.push({
date: nextDate,
value: Math.floor(Math.random() * 15 + 5)
})
}
return data;
}
<script src="//www.amcharts.com/lib/4/core.js"></script>
<script src="//www.amcharts.com/lib/4/charts.js"></script>
<div id="chartdiv" style="width: 100%; height: 98vh;"></div>

Using zoomCallback, how can I "snap" the zoom to existing x values?

I'm trying to use the zoomCallback function to set up interaction between my dygrpahs chart and a map chart. My x values are timestamps in seconds but since the sample rate is about 100Hz the timestamps are stored as float numbers.
The goal is that when dygraphs chart is zoomed in, the new x1 and x2 will be used to extract a piece of GPS track (lat, lng points). The extracted track will be used to re-fit the map boundaries - this will look like a "zoom in" on the map chart.
In my dygraphs options I specified the callback:
zoomCallback: function(x1,x2) {
let x1Index = graphHolder.getRowForX(x1);
let x2Index = graphHolder.getRowForX(x2);
// further code
}
But it looks like the zoom is not "snapped" to existing timestamp points so both x1Index and x2Index are null. Only when I zoom out, they'll correctly point to row 0 and the last row of data.
So the question is - is there a way to make the zoom snap only to the nearest existing x value so the row number can be returned? Or, is there an alternative to do what I want?
Thanks for any insights!
You can access the x-axis values via g.getValue(row, 0). From this you can either do a linear scan to find the first row in the range or (fancier but faster) use a binary search.
Here's a way to do the linear scan:
const [x1, x2] = g.xAxisRange();
let letRow = null, highRow = null;
for (let i = 0; i < g.numRows(); i++) {
if (g.getValue(i, 0) >= x1) {
lowRow = i;
break;
}
}
for (let i = g.numRows() - 1; i >= 0; i--) {
if (g.getValue(i, 0) <= x2) {
highRow = i;
break;
}
}
const dataX1 = g.getValue(lowRow, 0);
const dataX2 = g.getValue(highRow, 0);
For larger data sets you might want to do a binary search using something like lodash's _.sortedIndex.
Update Here's a binary search implementation. No promises about the exact behavior on the boundaries (i.e. whether it always returns indices that are inside the visible range or indices which contain the visible range).
function dygraphBinarySearch(g, x) {
let low = 0;
let high = g.numRows() - 1;
while (high > low) {
let i = Math.floor(low + (high - low) / 2);
const xi = g.getValue(i, 0);
if (xi < x) {
low = i + 1;
} else if (xi > x) {
high = i - 1;
} else {
return i;
}
}
return low;
}
function getVisibleDataRange(g) {
const [x1, x2] = g.xAxisRange();
let lowI = dygraphBinarySearch(g, x1);
let highI = dygraphBinarySearch(g, x2);
return [lowI, highI];
}

gwt visualization api labels disappear when displaying multiple charts

I just want to display several Charts in the same Panel. It doesn't matter which chart types I use (Column, Line, Pie etc). The result is that only the first chart has labels, no matter how many charts I try to display. See this screen shot:
On the second chart, the x- and y-axis labels are missing as well as the labels for the data sets. I tested in Chrome, Firefox and IE. Always the same.
Here is the code I use:
VerticalPanel panel=new VerticalPanel();
final int height = 400;
final int width = 1200;
Date d = new Date();
//message data
final DataTable msgData = DataTable.create();
msgData.addColumn(ColumnType.DATE, "date");
msgData.addColumn(ColumnType.NUMBER, "data one");
msgData.addColumn(ColumnType.NUMBER, "data two");
msgData.addRows(6);
for (int i = 0; i < 6; i++)
{
d.setTime(d.getTime() + (1000 * 60 * 60 * 24));
msgData.setValue(i, 0, d);
msgData.setValue(i, 1, i + 11);
msgData.setValue(i, 2, i + 12);
}
final Options options = Options.create();
options.setWidth(width);
options.setHeight(height);
options.setIsStacked(true);
options.setTitle("Chart One");
panel.add(new ColumnChart(msgData, options));
d = new Date();
//new data
final DataTable newData = DataTable.create();
newData.addColumn(ColumnType.DATE, "date");
newData.addColumn(ColumnType.NUMBER, "data three");
newData.addColumn(ColumnType.NUMBER, "data four");
newData.addRows(5);
for (int i = 0; i < 5; i++)
{
d.setTime(d.getTime() + (1000 * 60 * 60 * 24));
newData.setValue(i, 0, d);
newData.setValue(i, 1, i + 3);
newData.setValue(i, 2, i + 4);
}
final Options options_new = Options.create();
options_new.setWidth(width);
options_new.setHeight(height);
options_new.setIsStacked(true);
options_new.setTitle("Chart two");
panel.add(new ColumnChart(newData, options_new));
I checked the generated html with firebug. The charts are rendered using SVG and in the second chart there are just no svg-tags for the labels, while they exist in the first chart. So the missing labels are not cut off or hidden, but are not even created.
Thanks for your help