Bar width issue on achartengine - android

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()

Related

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.

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");

Error "Dataset and renderer should be not null and should have the same number of series" in Android

I am trying to display a graph with the data in the sqlitedatabase using AChartEngine library. I am having two records in database. BarChart graph displayed when there is one record. But with two records of data, it says, "Dataset and renderer should be not null and should have the same number of series". I dont understand this.
My code is,
Button ReportGraph = (Button) findViewById(R.id.ReportGraph);
ReportGraph.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GraphicalView GraphChartView = ChartFactory.getBarChartView(
getApplicationContext(), getWaterElectricityReading(),
getDemoRenderer(), Type.DEFAULT);
// Intent intent=ChartFactory.getLineChartIntent(this,
// getDemoDataset(), getDemoRenderer());
// startActivity(intent);
if (GraphChartView != null) {
GraphChartView.repaint();
}
relChartView.addView(GraphChartView);
mainLayout.setVisibility(View.GONE);
relChartView.setVisibility(View.VISIBLE);
}
});
private XYMultipleSeriesDataset getWaterElectricityReading() {
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd", Locale.US);
SimpleDateFormat df2 = new SimpleDateFormat("MMM dd yyyy");
Date StartDate;
Date EndDate;
String Pastdateformat = "";
String CurrentDateFormat = "";
SQLiteDatabase DB = Context
.openOrCreateDatabase("WaterElectricityReadingDataBase.db",
MODE_WORLD_READABLE, null);
Cursor c = DB
.rawQuery(
"select ReadingValue,strftime('%m/%d/%Y',StartDateTime) StartDateTime,strftime('%m/%d/%Y',EndDateTime) EndDateTime from WaterElectricity order by StartDateTime desc ",
null);
int rowCount = c.getCount();
if (c != null) {
if (rowCount > 0) {
if (c.moveToFirst()) {
do {
String ReadingValue = c.getString(c
.getColumnIndex("ReadingValue"));
String PastDate = c.getString(c
.getColumnIndex("StartDateTime"));
String CurrentDate = c.getString(c
.getColumnIndex("EndDateTime"));
try {
StartDate = df2.parse(PastDate);
Pastdateformat = sdf1.format(StartDate);
EndDate = df2.parse(CurrentDate);
CurrentDateFormat = sdf1.format(EndDate);
} catch (Exception e) {
}
XYSeries series = new XYSeries(
"WaterElectricityReading");
double ReadingVal = Double.parseDouble(ReadingValue);
series.add(rowCount, ReadingVal);
XYMultipleSeriesRenderer render = new XYMultipleSeriesRenderer();
dataset.addSeries(series);
rowCount++;
} while (c.moveToNext());
}
}
}
return dataset;
}
private XYMultipleSeriesRenderer getDemoRenderer() {
XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
renderer.setAxisTitleTextSize(12);
renderer.setChartTitleTextSize(12);
renderer.setLabelsTextSize(15);
renderer.setLegendTextSize(15);
renderer.setPointSize(5f);
renderer.setMargins(new int[] { 20, 30, 15, 0 });
XYSeriesRenderer r = new XYSeriesRenderer();
r.setColor(Color.GREEN);
r.setPointStyle(PointStyle.DIAMOND);
r.setFillBelowLine(false);
r.setFillPoints(true);
renderer.addSeriesRenderer(r);
setChartSettings(renderer);
return renderer;
}
private void setChartSettings(XYMultipleSeriesRenderer renderer) {
renderer.setChartTitle("Chart demo");
renderer.setXTitle("x values");
renderer.setYTitle("y values");
renderer.setApplyBackgroundColor(false);
renderer.setRange(new double[] { 0, 6, -70, 40 });
renderer.setFitLegend(false);
renderer.setAxesColor(Color.BLACK);
renderer.setShowGrid(true);
renderer.setXAxisMin(0);
renderer.setXAxisMax(10.5);
renderer.setYAxisMin(0);
renderer.setZoomEnabled(false);
renderer.setYAxisMax(1000);
}
For two records, I want two bars to be displayed.
Can anyone please point out the Mistake.
Any Help will be appreciated!!
Thanks.
Your chart should be built using one single XYMultipleSeriesDataset and one single XYMultipleSeriesRenderer.
The XYMultipleSeriesDataset should contain as many XYSeries as there are XYSeriesRenderer in XYMultipleSeriesRenderer.
In your code you are creating an XYSeries for each record, which is probably wrong. The data should be in the same series unless you have a good reason not to do that. However, if you add multiple XYSeries then you will need one XYSeriesRenderer for each XYSeries.

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});

Achartengine: Inserting dates as X-values in

I'm using AChartEngine to display averages across several days (2 months if possible). I'd like to provide a comparison between one individual and a group. At this point, I'm working on how to provide dates across the x-axis (ie, 12/15/2011 or Dec. 11, 2011 or even 12/15, Dec. 15).
I'm not sure how to do this in AchartEngine; the documentation is a little hard for me to follow without pictures (sorry). I'd like something like this: Using AChartEngine library for graphs, not able to get value for diffrent x-axis value
Here's my code:
private void setupHistoryChart() {
XYMultipleSeriesRenderer renderer = getBarDemoRenderer();
setChartSettings(renderer);
Intent intent = ChartFactory.getBarChartIntent(this, getBarDemoDataset(), renderer, Type.DEFAULT);
startActivity(intent);
}
public XYMultipleSeriesRenderer getBarDemoRenderer() {
XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
renderer.setAxisTitleTextSize(15);
renderer.setChartTitleTextSize(18);
renderer.setLabelsTextSize(12);
renderer.setLegendTextSize(15);
renderer.setMargins(new int[] {20, 30, 15, 0});
SimpleSeriesRenderer r = new SimpleSeriesRenderer();
r.setColor(Color.BLUE);
renderer.addSeriesRenderer(r);
return renderer;
}
private void setChartSettings(XYMultipleSeriesRenderer renderer) {
renderer.setChartTitle("History");
renderer.setChartTitleTextSize((float) 14.0);
renderer.setXTitle("Day");
renderer.setXLabelsAlign(Align.LEFT);
renderer.setYLabelsAlign(Align.LEFT);
renderer.setBarSpacing(0.5);
renderer.setZoomEnabled(true);
renderer.setZoomRate(0.2f);
renderer.setYTitle("Unit)");
renderer.setXAxisMin(1.0);
if(AppStatus.mDayMap.size() == 0){
renderer.setXAxisMax(3.0);
renderer.setYAxisMax(10.0);
}else{
renderer.setXAxisMax(AppStatus.mDayMap.size());
// Get the max Integer out of myMap
Map.Entry<String, Integer> maxEntry = null;
for (Map.Entry<String, Integer> entry : AppStatus.mDayMap.entrySet())
{
if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0)
{
maxEntry = entry;
}
}
renderer.setYAxisMax(maxEntry.getValue()/1000 + maxEntry.getValue()/1000);
}
renderer.setYAxisMin(0);
}
private XYMultipleSeriesDataset getBarDemoDataset() {
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
HashMap<String, Integer> myMap = AppStatus.mDayMap;
CategorySeries series = new CategorySeries ("Your History " + 1);
try{
if(AppStatus.mDayMap.size() == 0){
series.add(3.0);
series.add(10.0);
dataset.addSeries(series.toXYSeries());
}else{
Log.v(LOG_TAG, "Size of Map = " + myMap.size());
float sum = (float) 0.0;
if(myMap.size() > 0){
Iterator it = myMap.entrySet().iterator();
float j= (float)0.0;
for (int i = 0; i < 1 /*2*/; i++) {
//CategorySeries series = new CategorySeries("Your History " + (i + 1));
while(it.hasNext()){
Map.Entry pairs = (Map.Entry)it.next();
sum = sum + (float) (1.0 + j);
series.add((((Integer) pairs.getValue()).doubleValue())/1000);
}
dataset.addSeries(series.toXYSeries());
}
}
}
}catch(IllegalArgumentException e){
Log.e(LOG_TAG, "IllegalArgumentException " + e.toString());
series.add(3.0);
series.add(10.0);
dataset.addSeries(series.toXYSeries());
}
return dataset;
}
You can set custom text for the X axis labels:
renderer.addXTextLabel(x, text);
renderer.setXLabels(0);
In order to have multiple color bars in the bar chart, you will have to add multiple series.
There are some instructions here on how to download and run the demo application which includes a lot of good code to demonstrate the AChartEngine usage.

Categories

Resources