Can u please help me in creating a simple bar chart (for android) where the values are got from sqlite database. for eg consider the following table
year Units Sold
2001 2000
2002 2100
2003 1900
I need to create a bar graph with x-axis as year and y-axis as units sold . Can u Plz consider this as a request . I dont know how to import data from database .
first you have to fetch the values from the data base and stored into array with corresponding data type . Do like this.....
List<int[]> initial;
int[] my_year;
int[] my_units_sold;
public void onCreate()
{
int Column1 = net_db_cur.getColumnIndex("Year");
int Column2 = net_db_cur.getColumnIndex("Units Sold");
cur = sampleDB.rawQuery("SELECT * FROM " + Table_Name , null);
my_year = new int[columncount];
my_units_sold = new int[columncount];
if (cur.moveToFirst())
{
for (int i = 0; i < columncount; i++)
{
my_year [i] = net_db_cur.getInt(Column1);
my_units_sold[i] = net_db_cur.getInt(Column2);
cur.moveToNext();
}
}
initial = new ArrayList<int[]>();
initial1.add(my_year);
initial1.add(my_units_sold);
ll.addView(createBarChart(initial ,Color.BLUE,10,0,14,2000000,20000000,1,x_axis_labels1,x_axis_labels2,y_axis_labels1, y_axis_net_labels2,Color.parseColor("#ffffff")));
}
public View createBarChart(int[] values,int[] colors,int lable_text_size,int xMin,int xMax,int yMin,int yMax,double bar_space,double[] x_axis_lables1,String[] x_axis_lables2,double[] y_axis_lables1,String[] y_axis_lables2, int lable_color)
{
XYMultipleSeriesRenderer mrenderer = new XYMultipleSeriesRenderer();
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
/*for (int i = 0; i <values.length; i++)
{*/
CategorySeries series = new CategorySeries("");
/*double[] v = values.get(i);
int seriesLength = v.length;*/
for (int k = 0; k < values.length; k++)
{
series.add(values[k]);
}
dataset.addSeries(series.toXYSeries());
//}
//mrenderer.setMargins(new int[] { 10, 65, 10, 15 });
int color_length = colors.length;
for (int i = 0; i < color_length; i++)
{
SimpleSeriesRenderer r = new SimpleSeriesRenderer();
r.setColor(colors[i]);
r.setChartValuesSpacing(15);
mrenderer.addSeriesRenderer(r);
}
mrenderer.setOrientation(Orientation.HORIZONTAL);
mrenderer.setInScroll(false);
mrenderer.setGridColor(Color.BLACK);
mrenderer.setYLabelsAlign(Align.RIGHT);
mrenderer.setPanEnabled(false, false);
mrenderer.setZoomEnabled(false, false);
mrenderer.setBarSpacing(bar_space);
mrenderer.setLabelsTextSize(lable_text_size);
mrenderer.setAxesColor(Color.BLACK);
mrenderer.setXAxisMin(xMin);
mrenderer.setXAxisMax(xMax);
for(int i=0;i<x_axis_lables2.length;i++)
{
mrenderer.addXTextLabel(x_axis_lables1[i],x_axis_lables2[i]);
}
mrenderer.setYAxisMin(yMin);
mrenderer.setYAxisMax(yMax);
for(int j=0;j<y_axis_lables1.length;j++)
{
mrenderer.addYTextLabel(y_axis_lables1[j],y_axis_lables2[j]);
}
mrenderer.setLabelsColor(lable_color);
return (ChartFactory.getBarChartView(Income.this, dataset, mrenderer, Type.DEFAULT));
}
You will get the bar chart for with data base values. All the best.
Related
i have a graph view to implement an analysis graph
All the x-axis and y-axis data is get from the sqlite db data to show the output
x-axis is showing date
y-axis is showing weight
but I have no idea to implement them out, I am stuck,
below is my code but its wrong and I haven't completed yet, can someone help me to solve and build
DBHelperNote connect = new DBHelperNote(getActivity());
SQLiteDatabase db = connect.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM weight;",null);
String[] weight = new String[cursor.getCount()];
int i = 0;
while(cursor.moveToNext()){
d = cursor.getString(cursor.getColumnIndex("weightnum"));
weight[i] = d;
i++;
}
String[] date = new String[cursor.getCount()];
int r = 0;
while(cursor.moveToNext()){
e = cursor.getString(cursor.getColumnIndex("date"));
date[r] = e;
r++;
}
GraphView line_graph = (GraphView) contentView.findViewById(R.id.graph);
LineGraphSeries<DataPoint> line_series =
new LineGraphSeries<DataPoint>(new DataPoint[] {
>> here "while" getting error
while ( a!=weight.length) {
new DataPoint(Integer.parseInt(weight[i]), Integer.parseInt(date[i]));
i++;
}
}
);
line_graph.addSeries(line_series);
line_series.setDrawDataPoints(true);
line_series.setDataPointsRadius(10);
line_series.setOnDataPointTapListener(new OnDataPointTapListener() {
#Override
public void onTap(Series series, DataPointInterface dataPoint) {
Toast.makeText(getActivity(), "Series: On Data Point clicked: " + dataPoint, Toast.LENGTH_SHORT).show();
}
});
Hmn, it might be an error with the data type in their example they use a double instead of an int.
http://www.android-graphview.org/documentation/category/live-chart
private DataPoint[] generateData() {
int count = 30;
DataPoint[] values = new DataPoint[count];
for (int i=0; i<count; i++) {
double x = i;
double f = mRand.nextDouble()*0.15+0.3;
double y = Math.sin(i*f+2) + mRand.nextDouble()*0.3;
DataPoint v = new DataPoint(x, y);
values[i] = v;
}
return values;
I am using the MPAndroidChart library release v2. I'm trying to show 3 bars, with data taken from the database.
Unfortunately, instead of seeing 3 bars with their data, viewing them with the same result. See the screenshot. Thanks for your help.
int [] x = {1,2,3};
Cursor c = db.rawQuery(sql, null);
int count = c.getCount();
float value1 ;
float value2 ;
float value3 ;
String[] mesi = new String[count];
for(int n=0; n<count; n++) {
c.moveToNext();
mesi[n]= c.getString(0);
value1 = c.getFloat(1);
value2 = c.getFloat(2);
value3 = c.getFloat(3);
ArrayList<String> xVals = new ArrayList<String>();
for (int i = 0; i <x.length; i++) {
xVals.add(x.length + " " + mChart.getUnit());
}
ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();
ArrayList<BarEntry> yVals2 = new ArrayList<BarEntry>();
ArrayList<BarEntry> yVals3 = new ArrayList<BarEntry>();
for (int i = 0; i < x.length; i++) {
yVals1.add(new BarEntry(value1, i));
}
for (int i = 0; i < x.length; i++) {
yVals2.add(new BarEntry(value2, i));
}
for (int i = 0; i < x.length; i++) {
yVals3.add(new BarEntry(value3, i));
}
// create 3 datasets with different types
BarDataSet set1 = new BarDataSet(yVals1, "Company A");
set1.setColor(Color.rgb(104, 241, 175));
BarDataSet set2 = new BarDataSet(yVals2, "Company B");
set2.setColor(Color.rgb(164, 228, 251));
BarDataSet set3 = new BarDataSet(yVals3, "Company C");
set3.setColor(Color.rgb(242, 247, 158));
ArrayList<BarDataSet> dataSets = new ArrayList<BarDataSet>();
dataSets.add(set1);
dataSets.add(set2);
dataSets.add(set3);
BarData data = new BarData(xVals, dataSets);
// add space between the dataset groups in percent of bar-width
data.setGroupSpace(0);
mChart.setData(data);
mChart.invalidate();
}
c.close();
db.close();
}
the result
Did you make a logcat output of the values the chart should display?
Maybe they are not stored correctly in the database.
Your code seems correct to me.
You could also test it by simply providing a predefined value like e.g. 50 for all bars and see if it is plotted correctly.
To change the color call:
BarDataSet.setColor(...);
UPDATE: There is now a very detailed tutorial on how to create grouped BarCharts available on the official GitHub page of the library, based on release v3.0.0: Grouped BarChart tutorial
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]);
}
i just create a new chart with achartengine and i notice that when i move the chart it go over the x and y axis. thanks to Dan this problem solve by update my achartengine to 1.1.0 ver.
anyway i saw that this problem has been solve at the achartengine demoes but i can't understead why it doesn't fix the problem at my chart.
i guess it something that i do wrong, my xml code is :
<RelativeLayout
android:id="#+id/rlMyChartsGridDown"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/rlMyChartsTopGrid"
android:background="#drawable/weeks_grid_down" >
<LinearLayout
android:id="#+id/chart"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
/>
my java code is:
public GraphicalView weightView(Context context) {
manageData = new ManageData(context);
TimeSeries series = new TimeSeries("The day");
TimeSeries maxSeries = new TimeSeries("Max Weight");
TimeSeries minSeries = new TimeSeries("Min Weight");
int count = 0;
float sum = 0;
float max = 0;
int preWeek = 0;
manageData.open();
cursor = manageData.getProfile();
manageData.close();
if ((cursor.moveToFirst()) && (cursor.getCount() != 0)) {
weightUnit = cursor.getString(C_PROFILE_WEIGHT_UNIT);
weight = cursor.getFloat(C_PROFILE_WEIGHT);
bmi = cursor.getFloat(C_PROFILE_BMI);
weightGain();
cursor.close();
minSeries.add(0,weight);
maxSeries.add(0,weight);
minSeries.add(12,weight+1);
maxSeries.add(12,weight+2);
minSeries.add(42,weight+minWeight);
maxSeries.add(42,weight+maxWeight);
}
manageData.open();
Cursor cursor = manageData.getDiaryInfo();
manageData.close();
cursor.moveToFirst();
if (cursor.getCount() > 0) {
preWeek = cursor.getInt(DIARY_WEEK);
}
while (!cursor.isAfterLast()) {
if ((cursor.getInt(DIARY_WEEK) == preWeek)
&& (cursor.getFloat(WEIGHT) != 0)) {
count++;
sum = sum + cursor.getFloat(WEIGHT);
cursor.moveToNext();
} else {
if (count != 0) {
series.add(preWeek, sum / count);
if (max < sum / count) {
max = sum / count;
}
}
sum = 0;
count = 0;
preWeek = cursor.getInt(DIARY_WEEK);
if (cursor.getFloat(WEIGHT) != 0) {
count++;
sum = sum + cursor.getFloat(WEIGHT);
}
cursor.moveToNext();
}
}
if (max < sum / count) {
max = sum / count;
}
series.add(preWeek, sum / count);
cursor.close();
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
dataset.addSeries(series);
dataset.addSeries(minSeries);
dataset.addSeries(maxSeries);
XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
// Customization Weight line
XYSeriesRenderer renderer = new XYSeriesRenderer();
renderer.setColor(0xff154916);
renderer.setLineWidth(3);
renderer.setPointStyle(PointStyle.CIRCLE);
renderer.setFillPoints(true);
// Customization maxWeight line
XYSeriesRenderer rendererMax = new XYSeriesRenderer();
rendererMax.setColor(0xff8EC239);
rendererMax.setLineWidth(2);
// Customization minWeight line
XYSeriesRenderer rendererMin = new XYSeriesRenderer();
rendererMin.setColor(0xffF7931E);
rendererMin.setLineWidth(2);
mRenderer.setMargins(new int[] {20, 35, 20, 20 });
mRenderer.setApplyBackgroundColor(true);
mRenderer.setBackgroundColor(Color.TRANSPARENT);
mRenderer.setMarginsColor(color);
mRenderer.addSeriesRenderer(renderer);
mRenderer.addSeriesRenderer(rendererMax);
mRenderer.addSeriesRenderer(rendererMin);
mRenderer.setYLabelsColor(0, Color.BLACK);
mRenderer.setXLabelsColor(Color.BLACK);
mRenderer.setLabelsTextSize(18);
mRenderer.setAxesColor(Color.BLACK);
mRenderer.setLabelsColor(Color.BLACK);
mRenderer.setYLabelsAlign(Align.RIGHT);
// mRenderer.setYAxisAlign(Align.LEFT, 0);
mRenderer.setXTitle("Week");
if(weightUnit.equals("kg")){
mRenderer.setYTitle("Weight (kg)");
} else {
mRenderer.setYTitle("Weight (lb)");
}
mRenderer.setZoomButtonsVisible(true);
mRenderer.setLabelsColor(0xff418614);
mRenderer.setLegendTextSize(15);
mRenderer.setPointSize(5);
// mRenderer.setZoomEnabled(false, false);
// mRenderer.setPanEnabled(true, false);
mRenderer.setXAxisMax(43);
mRenderer.setXAxisMin(0);
if(max>maxWeight + weight){
mRenderer.setYAxisMax(max + 10);
} else {
mRenderer.setYAxisMax(maxWeight + weight + 10);
}
mRenderer.setYAxisMin(0);
return ChartFactory.getLineChartView(context, dataset, mRenderer);
}
my main java code is:
public void onClick(View v) {
switch (v.getId()) {
case R.id.tbMyChartsWeight:
tbMyChartsWeight.setChecked(true);
tbMyChartsWaist.setChecked(false);
tbMyChartsMood.setChecked(false);
line = new LineGraph();
gView = line.weightView(this);
layout = (LinearLayout) findViewById(R.id.chart);
layout.removeAllViews();
layout.addView(gView);
return;
case R.id.tbMyChartsWaist:
tbMyChartsWeight.setChecked(false);
tbMyChartsWaist.setChecked(true);
tbMyChartsMood.setChecked(false);
line = new LineGraph();
gView = line.waistView(this);
layout = (LinearLayout) findViewById(R.id.chart);
layout.removeAllViews();
layout.addView(gView);
return;
case R.id.tbMyChartsMood:
tbMyChartsWeight.setChecked(false);
tbMyChartsWaist.setChecked(false);
tbMyChartsMood.setChecked(true);
line = new LineGraph();
gView = line.mentalView(this);
layout = (LinearLayout) findViewById(R.id.chart);
layout.removeAllViews();
layout.addView(gView);
return;
default:
break;
}
}
i hope someone can help me with that
and i'm sorry for my bad english
thanks for you all :]
You are using a transparent background. You can fix this by using other background type or don't set any background.
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.