I have a CombinedChart and I would like that LineChart will take left axis as reference and BarChart will take right axis as reference but I could not get it out.
I am trying the following code:
barDataSet.setAxisDependency(YAxis.AxisDependency.RIGHT);
lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
but now both charts (LineChart and BarChart) are on the left (mixing them and right axis have disappeared).
Left and right axis have different granularity.
How can I properly make that each chart takes as reference one different Y axis (left or right respectively)?
Thanks in advance!
This is certainly possible in MPAndroidChart version 3.0.2.
As you can observe from the screenshot below, the LineDataSet has AxisDependency.LEFT (scaled from 0 - 21) while the BarDataSet has AxisDependency.RIGHT (scaled from 0 - 50) and, as required, they have different granularity:
Here is a proof of concept for generating the above chart that is a simple adaptation of the example project on GitHub:
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.WindowManager;
import com.github.mikephil.charting.charts.CombinedChart;
import com.github.mikephil.charting.charts.CombinedChart.DrawOrder;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.XAxis.XAxisPosition;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.CombinedData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import java.util.ArrayList;
public class CombinedChartActivity extends FragmentActivity {
private String[] mMonths = new String[] {
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"
};
private CombinedChart mChart;
private final int itemcount = 12;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_combined);
mChart = (CombinedChart) findViewById(R.id.chart1);
mChart.getDescription().setEnabled(false);
mChart.setBackgroundColor(Color.WHITE);
mChart.setDrawGridBackground(false);
mChart.setDrawBarShadow(false);
mChart.setHighlightFullBarEnabled(false);
mChart.setDrawOrder(new DrawOrder[]{
DrawOrder.BAR, DrawOrder.BUBBLE, DrawOrder.CANDLE, DrawOrder.LINE, DrawOrder.SCATTER
});
Legend l = mChart.getLegend();
l.setWordWrapEnabled(true);
l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
l.setDrawInside(false);
YAxis rightAxis = mChart.getAxisRight();
rightAxis.setDrawGridLines(false);
rightAxis.setGranularity(10f);
rightAxis.setAxisMinimum(0f);
YAxis leftAxis = mChart.getAxisLeft();
leftAxis.setDrawGridLines(false);
rightAxis.setGranularity(1f);
leftAxis.setAxisMinimum(0f);
XAxis xAxis = mChart.getXAxis();
xAxis.setPosition(XAxisPosition.BOTH_SIDED);
xAxis.setAxisMinimum(0f);
xAxis.setGranularity(1f);
xAxis.setValueFormatter(new IAxisValueFormatter() {
#Override
public String getFormattedValue(float value, AxisBase axis) {
return mMonths[(int) value % mMonths.length];
}
});
CombinedData data = new CombinedData();
data.setData(generateLineData());
data.setData(generateBarData());
xAxis.setAxisMaximum(data.getXMax() + 0.25f);
mChart.setData(data);
mChart.invalidate();
}
private LineData generateLineData() {
LineData d = new LineData();
ArrayList<Entry> entries = new ArrayList<Entry>();
for (int index = 0; index < itemcount; index++)
entries.add(new Entry(index + 0.5f, getRandom(15, 5)));
LineDataSet set = new LineDataSet(entries, "Line DataSet");
set.setColor(Color.rgb(0,100,0));
set.setLineWidth(2.5f);
set.setCircleColor(Color.rgb(0,100,0));
set.setCircleRadius(5f);
set.setFillColor(Color.rgb(0,100,0));
set.setMode(LineDataSet.Mode.CUBIC_BEZIER);
set.setDrawValues(true);
set.setValueTextSize(10f);
set.setValueTextColor(Color.rgb(0,100,0));
set.setAxisDependency(YAxis.AxisDependency.LEFT);
d.addDataSet(set);
return d;
}
private BarData generateBarData() {
ArrayList<BarEntry> entries = new ArrayList<BarEntry>();
for (int index = 0; index < itemcount; index++) {
entries.add(new BarEntry(index, getRandom(25, 25)));
}
BarDataSet set = new BarDataSet(entries, "Bar DataSet");
set.setColor(Color.rgb(60, 220, 78));
set.setValueTextColor(Color.rgb(60, 220, 78));
set.setValueTextSize(10f);
set.setAxisDependency(YAxis.AxisDependency.RIGHT);
return new BarData(set);
}
private float getRandom(float range, float startsfrom) {
return (float) (Math.random() * range) + startsfrom;
}
}
Related
I have a graph built using androidplot. I need to see each value horizontally (rotate 90 degrees). In the screenshot I showed what I mean. How to do it?
There is not a configuration option built in to do this, but it'd relatively easy to do in a custom renderer. Here's the quickstart example modified to do it:
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.annotation.NonNull;
import com.androidplot.ui.SeriesRenderer;
import com.androidplot.util.PixelUtils;
import com.androidplot.xy.CatmullRomInterpolator;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.LineAndPointRenderer;
import com.androidplot.xy.PointLabelFormatter;
import com.androidplot.xy.PointLabeler;
import com.androidplot.xy.SimpleXYSeries;
import com.androidplot.xy.XYGraphWidget;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYSeries;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.util.Arrays;
import java.util.List;
/**
* A simple XYPlot
*/
public class SimpleXYPlotActivity extends Activity {
private XYPlot plot;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_xy_plot_example);
// initialize our XYPlot reference:
plot = (XYPlot) findViewById(R.id.plot);
// create a couple arrays of y-values to plot:
final Number[] domainLabels = {1, 2, 3, 6, 7, 8, 9, 10, 13, 14};
Number[] series1Numbers = {1, 4, 2, 8, 4, 16, 8, 32, 16, 64};
Number[] series2Numbers = {5, 2, 10, 5, 20, 10, 40, 20, 80, 40};
// turn the above arrays into XYSeries':
// (Y_VALS_ONLY means use the element index as the x value)
XYSeries series1 = new SimpleXYSeries(
Arrays.asList(series1Numbers), SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "Series1");
XYSeries series2 = new SimpleXYSeries(
Arrays.asList(series2Numbers), SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "Series2");
// create formatters to use for drawing a series using LineAndPointRenderer
// and configure them from xml:
LineAndPointFormatter series1Format =
new MyLineAndPointFormatter(this, R.xml.line_point_formatter_with_labels);
LineAndPointFormatter series2Format =
new MyLineAndPointFormatter(this, R.xml.line_point_formatter_with_labels_2);
// add an "dash" effect to the series2 line:
series2Format.getLinePaint().setPathEffect(new DashPathEffect(new float[] {
// always use DP when specifying pixel sizes, to keep things consistent across devices:
PixelUtils.dpToPix(20),
PixelUtils.dpToPix(15)}, 0));
// (optional) add some smoothing to the lines:
// see: http://androidplot.com/smooth-curves-and-androidplot/
series1Format.setInterpolationParams(
new CatmullRomInterpolator.Params(10, CatmullRomInterpolator.Type.Centripetal));
series2Format.setInterpolationParams(
new CatmullRomInterpolator.Params(10, CatmullRomInterpolator.Type.Centripetal));
// add a new series' to the xyplot:
plot.addSeries(series1, series1Format);
plot.addSeries(series2, series2Format);
plot.getGraph().getLineLabelStyle(XYGraphWidget.Edge.BOTTOM).setFormat(new Format() {
#Override
public StringBuffer format(Object obj, #NonNull StringBuffer toAppendTo, #NonNull FieldPosition pos) {
int i = Math.round(((Number) obj).floatValue());
return toAppendTo.append(domainLabels[i]);
}
#Override
public Object parseObject(String source, #NonNull ParsePosition pos) {
return null;
}
});
}
/**
* A LineAndPointRenderer that rotates it's point labels -90 degrees.
*/
static class MyLineAndPointRenderer extends LineAndPointRenderer<MyLineAndPointFormatter> {
public MyLineAndPointRenderer(XYPlot plot) {
super(plot);
}
// Basically just copy the entire renderPoints implementation and add a rotation as shown below
#Override
protected void renderPoints(Canvas canvas, RectF plotArea, XYSeries series, int iStart, int iEnd, List<PointF> points,
LineAndPointFormatter formatter) {
if (formatter.hasVertexPaint() || formatter.hasPointLabelFormatter()) {
final Paint vertexPaint = formatter.hasVertexPaint() ? formatter.getVertexPaint() : null;
final boolean hasPointLabelFormatter = formatter.hasPointLabelFormatter();
final PointLabelFormatter plf = hasPointLabelFormatter ? formatter.getPointLabelFormatter() : null;
final PointLabeler pointLabeler = hasPointLabelFormatter ? formatter.getPointLabeler() : null;
for(int i = iStart; i < iEnd; i++) {
PointF p = points.get(i);
if(p != null) {
if (vertexPaint != null) {
canvas.drawPoint(p.x, p.y, vertexPaint);
}
if (pointLabeler != null) {
// this is where we rotate the text:
final int canvasState = canvas.save();
try {
canvas.rotate(-90, p.x, p.y);
canvas.drawText(pointLabeler.getLabel(series, i),
p.x + plf.hOffset, p.y + plf.vOffset, plf.getTextPaint());
} finally {
canvas.restoreToCount(canvasState);
}
}
}
}
}
}
}
static class MyLineAndPointFormatter extends LineAndPointFormatter {
// if you dont use configurator you can omit this constructor. this example uses it
// tho so here it is.
public MyLineAndPointFormatter(Context context, int xmlCfgId) {
super(context, xmlCfgId);
}
#Override
public Class<? extends SeriesRenderer> getRendererClass() {
return MyLineAndPointRenderer.class;
}
#Override
public SeriesRenderer doGetRendererInstance(XYPlot plot) {
return new MyLineAndPointRenderer(plot);
}
}
}
The important stuff is at the bottom in MyLineAndPointRenderer. Basically you're just extending LineAndPointRenderer and overriding renderPoints(...) to rotate the canvas -90 degrees before drawing the text labels, and then restore the canvas immediately after.
I am using MPANDROIDCHART library to show a chart,
in combine chart, I am showing Line chart and Bar Chart. My requirement is when Line checkbox true it should show line and when Bar checkbox is true it should show barchart.
When I uncheck line checkbox Line chart should hide.
and when uncheck bar checkbox bar chart should hide.
My code is working in case of Line but in case of Bar chart, it is not working I am getting the Nullpointer exception.
Below is my code.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context="com.swytch.chartdemo.MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/chechbToken"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="line" />
<CheckBox
android:id="#+id/chechbEnergy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bar" />
</LinearLayout>
<com.github.mikephil.charting.charts.CombinedChart
android:id="#+id/chart1"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
MainActivity.java
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import com.github.mikephil.charting.charts.CombinedChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.BubbleData;
import com.github.mikephil.charting.data.BubbleDataSet;
import com.github.mikephil.charting.data.BubbleEntry;
import com.github.mikephil.charting.data.CandleData;
import com.github.mikephil.charting.data.CandleDataSet;
import com.github.mikephil.charting.data.CandleEntry;
import com.github.mikephil.charting.data.ChartData;
import com.github.mikephil.charting.data.CombinedData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.data.ScatterDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private CombinedChart mChart;
private final int itemcount = 12;
private CheckBox chechmnb,chechabc;
protected String[] mMonths = new String[] {
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"
};
private XAxis xAxis;
private BarData barData;
private LineData lineData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
mChart = (CombinedChart) findViewById(R.id.chart1);
checkBoxInitialiozation();
chartInitialization();
setChartDataBasic();
}
private void checkBoxInitialiozation() {
chechabc = findViewById(R.id.chechbEnergy);
chechmnb = findViewById(R.id.chechbToken);
chechabc.setChecked(true);
chechmnb.setChecked(true);
chechabc.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (!b) {
if (!chechmnb.isChecked()) {
chechabc.setChecked(true);
} else {
chechabc.setChecked(false);
}
}
setChartData();
}
});
chechmnb.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton,
boolean b) {
if (!b) {
if (!chechabc.isChecked()) {
chechmnb.setChecked(true);
} else {
chechmnb.setChecked(false);
}
}
setChartData();
}
});
}
protected float getRandom(float range, float startsfrom) {
return (float) (Math.random() * range) + startsfrom;
}
private void chartInitialization() {
mChart.getDescription().setEnabled(false);
mChart.setBackgroundColor(Color.WHITE);
mChart.setDrawGridBackground(false);
mChart.setDrawBarShadow(false);
mChart.setHighlightFullBarEnabled(false);
// draw bars behind lines
mChart.setDrawOrder(new CombinedChart.DrawOrder[]{
CombinedChart.DrawOrder.BAR,CombinedChart.DrawOrder.LINE
});
Legend l = mChart.getLegend();
l.setWordWrapEnabled(true);
l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
l.setDrawInside(false);
YAxis rightAxis = mChart.getAxisRight();
rightAxis.setDrawGridLines(false);
rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
rightAxis.setEnabled(false);
YAxis leftAxis = mChart.getAxisLeft();
leftAxis.setDrawGridLines(false);
leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
xAxis = mChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setAxisMinimum(0f);
xAxis.setGranularity(1f);
}
private LineData generateLineData(ArrayList<Entry> entries) {
LineData d = new LineData();
LineDataSet set = new LineDataSet(entries, "Token");
set.setLineWidth(2.5f);
set.setCircleRadius(3f);
set.setCircleColor(getResources().getColor(R.color.colorAccent));
set.setColors(getResources().getColor(R.color.colorAccent));
set.setFillColor(getResources().getColor(R.color.colorPrimary));
set.setValueTextColor(getResources().getColor(R.color.colorPrimary));
set.setMode(LineDataSet.Mode.CUBIC_BEZIER);
set.setValueTextSize(10f);
set.setAxisDependency(YAxis.AxisDependency.LEFT);
//to draw value in side graph
set.setDrawValues(false);
d.addDataSet(set);
return d;
}
private BarData generateBarData(ArrayList<BarEntry> entries) {
BarDataSet set1 = new BarDataSet(entries, "Energy");
set1.setColor(getResources().getColor(R.color.colorPrimary));
set1.setValueTextColor(getResources().getColor(R.color.colorAccent));
set1.setValueTextSize(10f);
set1.setAxisDependency(YAxis.AxisDependency.LEFT);
//to draw value inside graph
set1.setDrawValues(false);
float barWidth = 0.45f; // x2 dataset
BarData d = new BarData(set1);
d.setBarWidth(barWidth);
return d;
}
private void setChartDataBasic() {
ArrayList<BarEntry> entriesBarEntry = new ArrayList<BarEntry>();
ArrayList<Entry> entriesLineEntry = new ArrayList<Entry>();
entriesBarEntry.clear();
entriesLineEntry.clear();
for (int index = 0; index < itemcount; index++)
entriesLineEntry.add(new Entry(index + 0.5f, getRandom(15, 5)));
entriesBarEntry = getBarEnteries(entriesBarEntry);
try {
if (mMonths.length > 0) {
xAxis.setValueFormatter(new IAxisValueFormatter() {
#Override
public String getFormattedValue(float value, AxisBase axis) {
return mMonths[(int) value % mMonths.length];
}
});
barData = generateBarData(entriesBarEntry);
lineData = generateLineData(entriesLineEntry);
setChartData();
} else {
mChart.setData(null);
mChart.notifyDataSetChanged();
mChart.invalidate();
}
} catch (ArithmeticException e) {
Log.d("MainActivity", "setChartData: " + e.getMessage());
}
}
public void setChartData() {
CombinedData chartData = new CombinedData();
if (chechabc.isChecked())
chartData.setData(barData);
if (chechmnb.isChecked())
chartData.setData(lineData);
xAxis.setAxisMaximum(chartData.getXMax() + 0.25f);
mChart.setData(chartData);
mChart.notifyDataSetChanged();
mChart.invalidate();
}
private ArrayList<BarEntry> getBarEnteries(ArrayList<BarEntry> entries) {
entries.add(new BarEntry(1, 20));
entries.add(new BarEntry(2, 10));
entries.add(new BarEntry(3, 80));
entries.add(new BarEntry(4, 40));
entries.add(new BarEntry(5, 20));
entries.add(new BarEntry(6, 60));
entries.add(new BarEntry(7, 22));
entries.add(new BarEntry(8, 15));
entries.add(new BarEntry(9, 45));
return entries;
}
}
Facing Exception
FATAL EXCEPTION: main
Process:
com.swytch.chartdemo, PID: 10510
java.lang.NullPointerException: Attempt to invoke virtual method 'int
com.github.mikephil.charting.data.BarData.getDataSetCount()' on a null
object reference
at
com.github.mikephil.charting.renderer.BarChartRenderer
.initBuffers(BarChartRenderer.java:61)
at
com.github.mikephil.charting.renderer.CombinedChartRenderer
.initBuffers(CombinedChartRenderer.java:82)
at
com.github.mikephil.charting.charts.BarLineChartBase
.notifyDataSetChanged(BarLineChartBase.java:326)
at
com.github.mikephil.charting.charts.Chart.setData(Chart.java:304)
at
com.github.mikephil.charting.charts.CombinedChart
.setData(CombinedChart.java:94)
at
com.swytch.chartdemo.MainActivity
.setChartData(MainActivity.java:240)
at
com.swytch.chartdemo.MainActivity$1
.onCheckedChanged(MainActivity.java:93)
at
android.widget.CompoundButton.setChecked(CompoundButton.java:154)
at
android.widget.CompoundButton.toggle(CompoundButton.java:113)
at
android.widget.CompoundButton.performClick(CompoundButton.java:118)
at
android.view.View$PerformClick.run(View.java:19884)
at
android.os.Handler.handleCallback(Handler.java:739)
at
android.os.Handler.dispatchMessage(Handler.java:95)
at
android.os.Looper.loop(Looper.java:135)
at
android.app.ActivityThread.main(ActivityThread.java:5343)
at
java.lang.reflect.Method.invoke(Native Method)
at
java.lang.reflect.Method.invoke(Method.java:372)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller
.run(ZygoteInit.java:905)
at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
OutputImage :-
Replace your setChartData method with:
public void setChartData()
{
CombinedData chartData = new CombinedData();
if(chechabc.isChecked() && chechmnb.isChecked())
{
chartData.setData(barData);
chartData.setData(lineData);
}
else if (chechabc.isChecked())
{
LineData ld = new LineData();
ld.clearValues();
chartData.setData(ld);
chartData.setData(barData);
}
else if (chechmnb.isChecked())
{
BarData bd = new BarData();
bd.clearValues();
chartData.setData(bd);
chartData.setData(lineData);
}
xAxis.setAxisMaximum(chartData.getXMax() + 0.25f);
mChart.setData(chartData);
mChart.notifyDataSetChanged();
mChart.invalidate();
}
Try changing your code as follows.
public void setChartData() {
CombinedData chartData = new CombinedData();
boolean dataAvailable = false;
if (chechabc.isChecked()) {
chartData.setData(barData);
dataAvailable = true;
}
if (chechmnb.isChecked()) {
chartData.setData(lineData);
dataAvailable = true;
}
if (dataAvailable) {
mChart.setData(chartData);
} else {
mChart.setData(null);
}
xAxis.setAxisMaximum(chartData.getXMax() + 0.25f);
mChart.notifyDataSetChanged();
mChart.invalidate();
}
I am developing line chart using achartengine 1.1.0.jar.
I am facing one issue when my final line chart is drawn.
The y axis labels drawn without vertical space between labels and all labels drawn together.
I have attached screen shot of my line chart drawn.
Here i am also attaching snippet code with it.
package com.example.simplelinecharexample;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer.Orientation;
import org.achartengine.renderer.XYSeriesRenderer;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.os.Bundle;
import android.widget.LinearLayout;
public class main extends Activity {
private GraphicalView mChart;
private String[] mMonth = new String[] { "Jan", "Feb", "Mar", "Apr", "May",
"Jun",
"Jul", "Aug" };
private String[] mweek = new String[] { "Mon", "Tue", "Wed", "Thu", "Fri",
"Sat",
"Sun" };
private String[] steps = new String[31];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int i = 0; i <= 15; i++)
if (i == 0)
steps[i] = String.valueOf(0);
else
steps[i] = String.valueOf(Integer.parseInt(steps[i - 1]) + 2000);
OpenChart();
}
private void OpenChart() {
int z[] = { 0, 1, 2, 3, 4, 5, 6, 7};
// int x[] = { 10, 18, 32, 21, 48, 60, 53, 80 };
int[] income = { 2000, 2500, 2700, 3000, 2800, 3500,5000 , 15000};
XYSeries xSeries = new XYSeries("X Series");
for (int i = 0; i < z.length; i++) {
xSeries.add(z[i], income[i]);
}
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
dataset.addSeries(xSeries);
XYSeriesRenderer Xrenderer = new XYSeriesRenderer();
Xrenderer.setColor(Color.RED);
Xrenderer.setPointStyle(PointStyle.DIAMOND);
Xrenderer.setDisplayChartValues(true);
Xrenderer.setLineWidth(5);
Xrenderer.setFillPoints(true);
XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
mRenderer.setChartTitle("X Vs Y Chart");`enter code here`
mRenderer.setXTitle("X Values");
mRenderer.setYTitle("Y Values");
mRenderer.setXLabels(0);![enter image description here][2]
mRenderer.setShowGrid(true);
mRenderer.setYLabels(49);
for (int i = 0; i < mweek.length; i++) {
mRenderer.addXTextLabel(i, mweek[i]);
}
mRenderer.addSeriesRenderer(Xrenderer);
mRenderer.setXLabelsAlign(Align.LEFT);
mRenderer.setYLabelsAlign(Align.RIGHT);
mRenderer.setLabelsTextSize(20);
mRenderer.setYAxisMin(0);
mRenderer.setXAxisMin(-1);
mRenderer.setYAxisMax(98000);
mRenderer.setPanEnabled(false, true);
mRenderer.setPanLimits(new double[]{0.0,Double.MAX_VALUE,0.0,98000});
mRenderer.setZoomEnabled(true, false);
mRenderer.setAntialiasing(true);
mRenderer.setMargins(new int[] { 60, 120, 60, 60 });
LinearLayout chart_container = (LinearLayout) findViewById(R.id.Chart_layout);
mChart = (GraphicalView) ChartFactory.getLineChartView(
getBaseContext(), dataset, mRenderer);
chart_container.addView(mChart);
}
}
I want add vertical space between y axis labels and it should auto scrollable.
Just replace your line
mRenderer.setYLabels(49);
to
mRenderer.setYLabels(10);
When you decrease the size of SetYlabels it will increase the space between Y labels.
Enjoy...
I am trying to develop an application with achart engine which draws a chart with multiple series .
Here is my code :
import java.util.ArrayList;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import android.content.Context;
import android.graphics.Color;
public class Graph {
private Context context;
XYMultipleSeriesDataset dataset;
XYMultipleSeriesRenderer renderer;
public static boolean ClickEnabled = true;
public Graph(Context context) {
this.context = context;
}
public void initData(ArrayList<Double> x,ArrayList<Double> y,ArrayList<Double> z){
XYSeries seriesX = new XYSeries("X");
for(int i =0 ; i< x.size();i++){
seriesX.add(x.get(i), i);
}
XYSeries seriesY = new XYSeries("Y");
for(int i =0 ; i< y.size();i++){
seriesY.add(y.get(i), i);
}
XYSeries seriesZ = new XYSeries("Z");
for(int i =0 ; i< z.size();i++){
seriesZ.add(z.get(i), i);
}
dataset = new XYMultipleSeriesDataset();
dataset.addSeries(seriesX);
dataset.addSeries(seriesY);
dataset.addSeries(seriesZ);
renderer = new XYMultipleSeriesRenderer();
}
public void setProperties(){
renderer.setPanEnabled(true, false);
renderer.setClickEnabled(ClickEnabled);
renderer.setBackgroundColor(Color.WHITE);
renderer.setApplyBackgroundColor(true);
renderer.setChartTitle("AccelerometerData");
renderer.setAxesColor(Color.BLACK);
XYSeriesRenderer renderer1 = new XYSeriesRenderer();
renderer1.setColor(Color.RED);
renderer1.setPointStyle(PointStyle.DIAMOND);
renderer.addSeriesRenderer(renderer1);
XYSeriesRenderer renderer2 = new XYSeriesRenderer();
renderer2.setColor(Color.GREEN);
renderer2.setPointStyle(PointStyle.DIAMOND);
renderer.addSeriesRenderer(renderer2);
XYSeriesRenderer renderer3 = new XYSeriesRenderer();
renderer3.setColor(Color.BLUE);
renderer3.setPointStyle(PointStyle.DIAMOND);
renderer.addSeriesRenderer(renderer3);
}
public GraphicalView getGraph(){
return ChartFactory.getLineChartView(context, dataset, renderer);
}
}
I am getting a chart like this:
I want all three series parallelly and want to remove black background from chart;
For Change the black color you can do like this
XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
renderer.setMargins(new int[] { top, left, bottom, right });
renderer.setMarginsColor(Color.RED);
and for your second problem plz be more specific by screenshot or any refrence image.
I am new to android. I am creating a bar chart using achartengine. I am not able to plot the bar chart. Can you please tell me what am I doing wrong here. I have created a database using sqlite data browser and copied the data base into the assets folder of my project.
I had written a code to draw the bar chart with static values and now i modified it to take values from a database.
package flu.solutions.travelsense;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.achartengine.ChartFactory;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer.Orientation;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
public class ChartActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
XYMultipleSeriesRenderer renderer = getBarDemoRenderer();
setChartSettings(renderer);
Intent intent = ChartFactory.getBarChartIntent(this, getBarDemoDataset(), renderer, Type.DEFAULT);
startActivity(intent);
}
public Intent createIntent()
{
String[] titles = new String[] { "Top 10 Destinations", " " };
List<double[]> values = new ArrayList<double[]>();
values.add(new double[] { 8, 6, 4, 6, 7, 7, 9, 5, 7, 8, 8 });
values.add(new double[] {});
int[] colors = new int[] { Color.RED, Color.BLACK};
XYMultipleSeriesRenderer renderer = buildBarRenderer(colors);
renderer.setOrientation(Orientation.HORIZONTAL);
setChartSettings(renderer);
renderer.setXLabels(1);
renderer.setYLabels(10);
renderer.addXTextLabel(1, "Bangalore");
renderer.addXTextLabel(2, "Mysore");
renderer.addXTextLabel(3, "Chennai");
renderer.addXTextLabel(4, "Delhi");
renderer.addXTextLabel(5, "Kolkatta");
renderer.addXTextLabel(6, "Kashmir");
renderer.addXTextLabel(7, "Hyderabad");
renderer.addXTextLabel(8, "Mumbai");
renderer.addXTextLabel(9, "Kerala");
renderer.addXTextLabel(10, "Gujarat");
int length = renderer.getSeriesRendererCount();
for (int i = 0; i < length; i++)
{
SimpleSeriesRenderer seriesRenderer = renderer.getSeriesRendererAt(i);
seriesRenderer.setDisplayChartValues(false);
}
return ChartFactory.getBarChartIntent(this, buildBarDataset(titles, values), renderer,Type.DEFAULT);
}
public XYMultipleSeriesRenderer getBarDemoRenderer() {
XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
renderer.setAxisTitleTextSize(16);
renderer.setChartTitleTextSize(20);
renderer.setLabelsTextSize(15);
renderer.setLegendTextSize(15);
renderer.setMargins(new int[] {20, 30, 15, 0});
SimpleSeriesRenderer r = new SimpleSeriesRenderer();
r.setColor(Color.BLUE);
renderer.addSeriesRenderer(r);
r = new SimpleSeriesRenderer();
r.setColor(Color.GREEN);
renderer.addSeriesRenderer(r);
return renderer;
}
private XYMultipleSeriesDataset getBarDemoDataset() {
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
final int nr = 10;
Random r = new Random();
int SERIES_NR = 2;
for (int i = 0; i < SERIES_NR; i++) {
CategorySeries series = new CategorySeries("Demo series " + (i + 1));
for (int k = 0; k < nr; k++) {
series.add(100 + r.nextInt() % 100);
}
dataset.addSeries(series.toXYSeries());
}
return dataset;
}
private void setChartSettings(XYMultipleSeriesRenderer renderer) {
renderer.setChartTitle("Chart demo");
renderer.setXTitle("x values");
renderer.setYTitle("y values");
renderer.setXAxisMin(0);
renderer.setXAxisMax(5);
renderer.setYAxisMin(0);
renderer.setYAxisMax(250);
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_chart, menu);
return true;
}
}
your createIntent() method doesn't even look like its been referenced. i believe that the correct OnCreate would be:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = createIntent();
startActivity(intent);
}
But you should know that you're eventually going to want to make your graph load as view rather than intent to get the real-time functionality that you wanted.