Android achartengine simple pie chart - android

I'm following an example in this link and
created a class as below
public class aChartExample {
public Intent execute(Context context) {
int[] colors = new int[] { Color.RED, Color.YELLOW, Color.BLUE };
DefaultRenderer renderer = buildCategoryRenderer(colors);
CategorySeries categorySeries = new CategorySeries("Vehicles Chart");
categorySeries.add("cars ", 30);
categorySeries.add("trucks", 20);
categorySeries.add("bikes ", 60);
return ChartFactory.getPieChartIntent(context, categorySeries, renderer, null);
}
protected DefaultRenderer buildCategoryRenderer(int[] colors) {
DefaultRenderer renderer = new DefaultRenderer();
for (int color : colors) {
SimpleSeriesRenderer r = new SimpleSeriesRenderer();
r.setColor(color);
renderer.addSeriesRenderer(r);
}
return renderer;
}
}
and I'm calling it when my app starts on my starting activity in the onCreate.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mainpage);
Intent achartIntent = new aChartExample().execute(this);
startActivity(achartIntent);
}
I then included the achartengine-0.6.0.jar in my project.
When I run the app it crashes on the startActivity line.
Not sure where to go from here.

Did you add this below line in AndroidManifest.xml. If so can you post the error message, I tried the same example 2 days ago and worked for me.
<activity android:name="org.achartengine.GraphicalActivity">

startActivity takes only activities. Not for all classes.

final CategorySeries series = new CategorySeries("pie");
for (int i = 0; i < Xaxes_value.size(); i++) {
series.add(Xaxes_value.get(i) + "",
Long.parseLong(yaxes_value.get(i)));
}
List<Integer> colors = new ArrayList<Integer>();
int[] colorr = { Color.parseColor("#56ADDB"),
Color.parseColor("#F59331"), Color.parseColor("#73C83C"),
Color.parseColor("#948D8B"), Color.parseColor("#E54273"),
Color.parseColor("#FFD34E"), Color.parseColor("#2A86D6"),
Color.parseColor("#00BFC0"), Color.parseColor("#95AC5F"),
Color.parseColor("#FF8497") };
for (int i = 0; i < yaxes_value.size(); i++) {
colors.add(colorr[i]);
}
renderer = new DefaultRenderer();
for (int color = 0; color < colors.size(); color++) {
SimpleSeriesRenderer r = new SimpleSeriesRenderer();
r.setColor(colors.get(color));
r.setDisplayBoundingPoints(false);
// r.setDisplayChartValuesDistance(20);
r.setDisplayChartValues(false);
r.setChartValuesTextSize(18);
r.setStroke(BasicStroke.SOLID);
renderer.addSeriesRenderer(r);
}
// renderer.isInScroll();
renderer.setZoomEnabled(false);
renderer.setPanEnabled(false);
renderer.setZoomButtonsVisible(false); // set zoom button in Graph
renderer.setApplyBackgroundColor(false);
renderer.setBackgroundColor(Color.WHITE); // set background color
renderer.setChartTitle("Pie Chart");
renderer.setLabelsColor(Color.BLACK);
renderer.setMargins(new int[] { 20, 100, 20, 15 });
renderer.setLabelsTextSize(20);
renderer.setChartTitleTextSize((float) 30);
renderer.setShowLabels(false);
renderer.setLegendTextSize(25);
renderer.setDisplayValues(true);
renderer.setStartAngle(90);
GraphicalView mChart = ChartFactory.getPieChartView(getApplicationContext(), series,
renderer);
layout_graph.addView(mChart);

Related

Bar width issue on achartengine

I have a problem with my chart using achartengine. I set data for dataset from my sqlite db, I can show it successfully on the chart but the bar width is to narrow. Here are my GenerateEngine class to generate bar from sqlite db.
public class GenerateChart {
private ExpensesDataSource datasource;
private SpinnerValues spinnerValues = new SpinnerValues();
private SimpleDateFormat monthFormat, yearFormat;
String month, year;
List<String> values;
XYSeries series;
public XYMultipleSeriesDataset getExpensesBarDataset(Context context) {
datasource = new ExpensesDataSource(context);
monthFormat = new SimpleDateFormat("MM");
month = monthFormat.format(new Date());
yearFormat = new SimpleDateFormat("yyyy");
year = yearFormat.format(new Date());
datasource.openToRead();
values = datasource.GetTotalEachCategory(month, year);
datasource.close();
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
XYSeries series;
for(int i = 0; i < spinnerValues.categoryText.length; i++) {
series = new XYSeries(spinnerValues.categoryText[i]);
series.add(i, Double.parseDouble(values.get(i)));
dataset.addSeries(series);
}
return dataset;
}
public XYMultipleSeriesRenderer getExpensesBarRenderer() {
XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
renderer.setAxisTitleTextSize(16);
renderer.setChartTitleTextSize(20);
renderer.setLabelsTextSize(15);
renderer.setLegendTextSize(15);
renderer.setMargins(new int[] { 30, 40, 15, 0 });
XYSeriesRenderer r;
for(int i = 0; i < spinnerValues.categoryColor.length; i++) {
r = new XYSeriesRenderer();
r.setColor(Color.parseColor(spinnerValues.categoryColor[i]));
r.setLineWidth(20);
r.setFillPoints(true);
r.setDisplayChartValues(true);
renderer.addSeriesRenderer(r);
}
return renderer;
}
public void myChartSettings(XYMultipleSeriesRenderer renderer, String month, String year) {
renderer.setChartTitle("Pratinjau Grafik Pengeluaran Bulan " + month + " Tahun " + year);
renderer.setXAxisMin(-10);
renderer.setXAxisMax(10);
renderer.setYAxisMin(0);
renderer.setYAxisMax(500000);
renderer.setYLabelsAlign(Paint.Align.RIGHT);
renderer.setBarSpacing(.1);
renderer.setXTitle("Kategori");
renderer.setYTitle("Total Pengeluaran");
renderer.setShowGrid(true);
renderer.setGridColor(Color.GRAY);
renderer.setZoomButtonsVisible(true);
renderer.setXLabels(0); // sets the number of integer labels to appear
}}
Here is what I got from my class.
I want to add the width of the bar so it will proper. I will appreciate any help, thank you.
setBarWidth api is used for XYMultipleSeriesRenderer
Refer this Api -->API
So in ur code u need to change this :
Inside getExpensesBarRenderer() Api
renderer.setBarWidth()

sometimes line doesn't shows on the graph- a chartengine

I have developed a application using a chart engine. and am using achartengine for drawing graphs.
I have drawn a graph using time chart. here dates are coming on x-axis and values on y axis. When the input dates are too long ie, if one date is jan-10 and 2nd date is apr 12 then the line between two points doesn't showing.
![enter image description here][there is another point on date jan 10 is there when we scroll we can see that but the line between point is not showing]1
this is code
public View getChartView(long startDate,long currentDate,int visibility)
{
String titles = "New tickets";
Date[]dateList = new Date[dates.length];
for(int i=0;i<dates.length;i++)
{
dateList[i]=convertDateFromString(dates[i]);
}
int[] colors = new int[] { Color.GREEN};
PointStyle[] styles = new PointStyle[] { PointStyle.CIRCLE};
XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
setChartSettings(renderer, "Project work status", "Date", "Tickets",startDate,
currentDate,yMin,yMax, Color.GRAY, Color.LTGRAY);
float textSize=context.getResources().getDimension(R.dimen.text_title_medium);
CustomTimeChart chart2 = new CustomTimeChart(
buildDateDataset(titles, dateList, values), renderer,context,visibility,textSize);
// TimeChart chart = new TimeChart(buildDateDataset(titles, dateList, values), renderer);
chart2.setDateFormat("dd,MMM");
final GraphicalView graphView = new GraphicalView(context, chart2);
graphView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
SeriesSelection ss = graphView.getCurrentSeriesAndPoint();
if(ss!=null)
{
long clickedDateSeconds = (long) ss.getXValue();
Date clickedDate = new Date(clickedDateSeconds);
WeightTrackingActivity.dateCal.setTime(clickedDate);
WeightTrackingActivity.weight = ss.getValue();
try {
clickedDate=formatter.parse(clickedDate.toString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(clickedDate.before(Funcs.getCurrentDateInDate()))
WeightTrackingActivity.btnRecordWeight.setText("Update weight");
else
WeightTrackingActivity.btnRecordWeight.setText(WeightTrackingActivity.weightBtnText);
}
else
{
WeightTrackingActivity.btnRecordWeight.setText(WeightTrackingActivity.weightBtnText);
WeightTrackingActivity.dateCal.setTime(new Date());
}
}
});
return graphView;
}
protected void setChartSettings(XYMultipleSeriesRenderer renderer, String title, String xTitle,
String yTitle, double startDate, double currentDate, double yMin, double yMax, int axesColor,
int labelsColor) {
// renderer.setAxesColor(axesColor);
renderer.setApplyBackgroundColor(true);
renderer.setBackgroundColor(Color.WHITE);
renderer.setShowGrid(true);
renderer.setGridColor(Color.LTGRAY);
renderer.setShowLegend(false);
renderer.setMarginsColor(Color.WHITE);
// renderer.setPanEnabled(true, true);
renderer.setClickEnabled(true);
// renderer.setPanLimits(new double[]{yMin,yMax});
renderer.setZoomEnabled(true, false);
renderer.setLabelsTextSize(context.getResources().getDimension(R.dimen.text_title_medium));
renderer.setPointSize(5f);
renderer.setXAxisMin(startDate);
renderer.setXAxisMax(currentDate);
renderer.setXLabelsColor(Color.BLACK);
renderer.setXLabels(5);
renderer.setXLabelsPadding(2);
renderer.setYAxisMin(yMin);
renderer.setYAxisMax(yMax);
renderer.setYLabels(6);
renderer.setYLabelsColor(0, Color.WHITE);
renderer.setYLabelsAlign(Align.RIGHT);
renderer.setYLabelsPadding(2);
}
protected XYMultipleSeriesDataset buildDateDataset(String titles,Date[] xValues,
double[] yValues) {
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
TimeSeries series = new TimeSeries(titles);
sortingValues(xValues,yValues);
for (int k = 0; k < xValues.length; k++) {
series.add(xValues[k], yValues[k]);
}
dataset.addSeries(series);
return dataset;
}
private void sortingValues(Date[] xValues, double[] yValues) {
for(int i=0;i<xValues.length;i++)
{
for(int j=0;j<xValues.length-1;j++)
{
if(xValues[i].before(xValues[j]))
{
Date d = xValues[i];
xValues[i]=xValues[j];
xValues[j]=d;
Double x=yValues[i];
yValues[i]=yValues[j];
yValues[j]=x;
}
}
}
}
protected XYMultipleSeriesRenderer buildRenderer(int[] colors, PointStyle[] styles) {
XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
setRenderer(renderer, colors, styles);
return renderer;
}
protected void setRenderer(XYMultipleSeriesRenderer renderer, int[] colors, PointStyle[] styles) {
renderer.setMargins(new int[] { 20, 40, 15, 20 });
int length = colors.length;
for (int i = 0; i < length; i++) {
XYSeriesRenderer r = new XYSeriesRenderer();
r.setColor(colors[i]);
r.setPointStyle(styles[i]);
r.setFillPoints(true);
r.setLineWidth(3);
r.setDisplayChartValues(true);
r.setChartValuesTextSize(context.getResources().getDimension(R.dimen.text_title_small));
r.setDisplayChartValuesDistance(2);
FillOutsideLine fillOutsideLine=new FillOutsideLine(FillOutsideLine.Type.BELOW);
fillOutsideLine.setColor(Color.parseColor("#A3E0FF"));
r.addFillOutsideLine(fillOutsideLine);
renderer.addSeriesRenderer(r);
}
}
private Date convertDateFromString(String date) {
Date dateConverted = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
dateConverted = df.parse(date);
} catch ( ParseException e ) {
}
return dateConverted;
}
you can turn hardware acceleration off
android:hardwareAccelerated="false"
to disable it for a particular view (This worked for me)
try:
View.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
I've added this after rendering the graph but it should work everywhere.

combination of two bar chart and two line chart using aChartEngine in Android

below code to combine two bar and two line chart :
public class GraphCombination {
private Context context;
private String[] weekDays = new String[] { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thrusday", "Friday", "Saturday" };
private XYSeriesRenderer lowestTempBarRenderer, highestTempBarRenderer,
lowestTempLineRenderer, highestTempLineRenderer;
private XYMultipleSeriesRenderer multiRenderer;
private int margins[] = { 50, 50, 50, 50 };
public GraphCombination(Context context) {
this.context = context;
}
public void drawChart() {
int days[] = { 0, 1, 2, 3, 4, 5, 6 };
double lowestTemp[] = { 23.5, 25.2, 27.8, 21.2, 26.3, 27.1, 22.6 };
double highestTemp[] = { 38.2, 39.4, 40.8, 36.1, 39.9, 41.1, 38.5 };
XYSeries lowestTempSeries = new XYSeries("Lowest Temperature");
XYSeries highestTempSeries = new XYSeries("Highest Temperature");
for (int i = 0; i < days.length; i++) {
lowestTempSeries.add(i, lowestTemp[i]);
highestTempSeries.add(i, highestTemp[i]);
}
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
dataset.addSeries(highestTempSeries);
dataset.addSeries(lowestTempSeries);
dataset.addSeries(highestTempSeries);
dataset.addSeries(lowestTempSeries);
setLowestTempBarRenderer();
setHighestTempBarRenderer();
setLowestTempLineRenderer();
setHighestTempLineRenderer();
setMultiRenderer();
for (int i = 0; i < days.length; i++) {
multiRenderer.addXTextLabel(i, weekDays[i]);
}
multiRenderer.addSeriesRenderer(highestTempBarRenderer);
multiRenderer.addSeriesRenderer(lowestTempBarRenderer);
multiRenderer.addSeriesRenderer(highestTempLineRenderer);
multiRenderer.addSeriesRenderer(lowestTempLineRenderer);
Intent intent = ChartFactory.getCombinedXYChartIntent(context, dataset,
multiRenderer, new String[] { BarChart.TYPE, BarChart.TYPE,
LineChart.TYPE, LineChart.TYPE }, "Combined Chart");
context.startActivity(intent);
}
private void setLowestTempBarRenderer() {
lowestTempBarRenderer = new XYSeriesRenderer();
lowestTempBarRenderer.setColor(context.getResources().getColor(
R.color.lowTemp));
lowestTempBarRenderer.setFillPoints(true);
lowestTempBarRenderer.setLineWidth(1);
lowestTempBarRenderer.setChartValuesTextAlign(Align.RIGHT);
lowestTempBarRenderer.setChartValuesTextSize(15f);
lowestTempBarRenderer.setDisplayChartValues(true);
}
private void setHighestTempBarRenderer() {
highestTempBarRenderer = new XYSeriesRenderer();
highestTempBarRenderer.setColor(context.getResources().getColor(
R.color.highTemp));
highestTempBarRenderer.setFillPoints(true);
highestTempBarRenderer.setLineWidth(1);
highestTempBarRenderer.setChartValuesTextAlign(Align.RIGHT);
highestTempBarRenderer.setChartValuesTextSize(15f);
highestTempBarRenderer.setDisplayChartValues(true);
}
private void setMultiRenderer() {
multiRenderer = new XYMultipleSeriesRenderer();
multiRenderer.setChartTitle("Bar Chart and Line Chart");
multiRenderer.setXTitle("Week Days");
multiRenderer.setYTitle("Temperature in celsius");
multiRenderer.setXAxisMin(-1);
multiRenderer.setXAxisMax(7);
multiRenderer.setYAxisMin(15);
multiRenderer.setYAxisMax(45);
multiRenderer.setLabelsTextSize(17f);
multiRenderer.setLegendTextSize(20f);
multiRenderer.setAxisTitleTextSize(25f);
multiRenderer.setMargins(margins);
multiRenderer.setChartTitleTextSize(30f);
multiRenderer.setApplyBackgroundColor(true);
multiRenderer.setBackgroundColor(context.getResources().getColor(
R.color.background));
multiRenderer.setYLabelsAlign(Align.RIGHT);
multiRenderer.setBarSpacing(1);
multiRenderer.setZoomButtonsVisible(false);
multiRenderer.setPanEnabled(false);
multiRenderer.setXLabels(0);
}
private void setLowestTempLineRenderer() {
lowestTempLineRenderer = new XYSeriesRenderer();
lowestTempLineRenderer.setColor(context.getResources().getColor(
R.color.lowTemp));
lowestTempLineRenderer.setFillPoints(true);
lowestTempLineRenderer.setLineWidth(3);
lowestTempLineRenderer.setChartValuesTextAlign(Align.CENTER);
lowestTempLineRenderer.setChartValuesTextSize(15f);
lowestTempLineRenderer.setDisplayChartValues(false);
}
private void setHighestTempLineRenderer() {
highestTempLineRenderer = new XYSeriesRenderer();
highestTempLineRenderer.setColor(context.getResources().getColor(
R.color.highTemp));
highestTempLineRenderer.setFillPoints(true);
highestTempLineRenderer.setLineWidth(3);
highestTempLineRenderer.setChartValuesTextAlign(Align.CENTER);
highestTempLineRenderer.setChartValuesTextSize(15f);
highestTempLineRenderer.setDisplayChartValues(false);
}
}
due to above code i got this type of graph :
and i want this type of graph :
so how to avoid overlapping in two bar chart..??
just change this one
for (int i = 0; i < days.length; i++) {
lowestTempSeries.add(i, lowestTemp[i]);
highestTempSeries.add(i, highestTemp[i]);
}
with this :
for (int i = 0, j = 0; i < days.length; i++, j += 2) {
lowestTempSeries.add(j, lowestTemp[i]);
highestTempSeries.add(j + 0.9, highestTemp[i]);
}
and also change this :
for (int i = 0; i < days.length; i++) {
multiRenderer.addXTextLabel(i, weekDays[i]);
}
with this :
for (int i = 0, j = 1; i < days.length; i++, j += 2) {
multiRenderer.addXTextLabel(j - 0.5, weekDays[i]);
}

how to change display value of x axis in bar graph-achartengine

I'm using achartengine library forline graph.Instead of timestamp how can i show date in x-axis
my code is
public GraphicalView getLine(Context context, LinkedHashMap<String, List<Item>> data, String value2, String value3) {
List<TimeSeries> series=new ArrayList<TimeSeries>();
Set<String> keys = data.keySet();
for(String key:keys)
{
TimeSeries series1 = new TimeSeries(key);
List<Item> value=data.get(key);
for(Item itm:value)
{
Double temp=Double.parseDouble(itm.getDataItem(value3));
String temp1=null;
if(value2.equals("created_time"))
{
temp1=itm.getCreated_time();
}
else
{
try
{
temp1=itm.getModified_time();
}
catch (NullPointerException e) {
temp1=itm.getCreated_time();
}
}
Timestamp timestamp = new Timestamp(Integer.parseInt(temp1.substring(0,10)));
Date date = new Date(timestamp.getTime()*1000);
series1.add(date,temp);
}
series.add(series1);
}
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
for(TimeSeries serie:series)
{
dataset.addSeries(serie);
}
XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer(); // Holds a collection of XYSeriesRenderer and customizes the graph
mRenderer.setBackgroundColor(Color.BLACK);
mRenderer.setZoomEnabled(true);
mRenderer.setAntialiasing(true);
for(TimeSeries serie:series)
{
XYSeriesRenderer renderer = new XYSeriesRenderer(); // This will be used to customize line 1
mRenderer.addSeriesRenderer(renderer);
int color;
Random rnd = new Random();
color = Color.argb(200, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
renderer.setColor(color);
renderer.setPointStyle(PointStyle.CIRCLE);
renderer.setFillPoints(true);
}
return ChartFactory.getLineChartView(context, dataset, mRenderer);
}
You can set custom labels:
renderer.addXTextLabel(x, formattedDate);
i found a better solution
ChartFactory.getTimeChartView(context, dataset,mRenderer, "DD-MM-YYY");

achart engine settings

I've tried to use achart engine but the documentation is somewhat unclear. I've also tried looking through the examples.
Could someone explain how to increase the thickness of the lines in the bar graph that's attached? Also, I would like to separate each bar into it's own series but I haven't had luck doing so (my code is below the image). I've been working on this issue for a really long time!
public XYMultipleSeriesRenderer getBarDemoRenderer() {
Log.d(LOG_TAG, "Entering getBarDemoRenderer");
XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
renderer.setAxisTitleTextSize(18);
renderer.setChartTitleTextSize(20);
renderer.setLabelsTextSize(18);
renderer.setLegendTextSize(14);
renderer.setMargins(new int[] {20, 30, 15, 0});
int[] color = {Color.RED, Color.CYAN,Color.YELLOW, Color.LTGRAY,Color.MAGENTA, Color.GREEN, Color.WHITE};
for(int i=0; i<7; i++){
SimpleSeriesRenderer r = new SimpleSeriesRenderer();
r.setColor(color[i]);
renderer.addSeriesRenderer(r);
}
int renderCount = renderer.getSeriesRendererCount();
Log.d(LOG_TAG, "Renderer series count = " + renderCount);
return renderer;
}
private XYMultipleSeriesDataset getApplianceDataset() {
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
try{
CategorySeries series = null;
for (Map.Entry<String,Float> entry : list.entrySet()) {
String key = entry.getKey();
series = new CategorySeries (key);
String b=String.valueOf(entry.getValue());
double value=Double.valueOf(b);
series.add(value);
dataset.addSeries(series.toXYSeries());
}
}catch(IllegalArgumentException e){
Log.e(LOG_TAG, "IllegalArgumentException " + e.toString());
Toast.makeText(this, "Unable to show chart", Toast.LENGTH_LONG).show();
}
int dataSeriesCount = dataset.getSeriesCount();
return dataset;
}
private void setChartSettings(XYMultipleSeriesRenderer renderer) {
renderer.setChartTitle("Test Bar Chart");
renderer.setChartTitleTextSize(20);
renderer.setXTitle("Appliance");
renderer.setYTitle("Watt Hours (wh)");
renderer.setXAxisMax(3);
renderer.setXAxisMin(0.0);
renderer.setYAxisMax(1800);
renderer.setYAxisMin(0);
}
in setChartSettings give
renderer.setBarSpacing(1.0f);
renderer.setMargins(new int[] {10, 10, 10, 0});

Categories

Resources