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});
Related
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()
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.
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.
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.
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);