I'm using MPandroidCharts in android application to make a bar chart it data from NodeJs server my code works fine but I found that when I change nbs of data (number of articles "on XAxe" < 5) the label nb and size still the some ( max 5 elements) that make my graph Not understood, I need a solution plz
to understand my situation plz look at pictures:
My code:
ArrayList<BarEntry> entries = new ArrayList<>();
final ArrayList<String> months = new ArrayList<>();
Log.d("liste size ",product_List.size()+"");
for(int i=0; i<product_List.size();i++){
Log.d("get List nb ",product_List.get(i).getId());
Log.d("get List produit ",product_List.get(i).getProduit());
months.add(i,product_List.get(i).getProduit());
int nb = Integer.parseInt(product_List.get(i).getId());
entries.add(new BarEntry(i, nb));
}
BarDataSet barDataSet = new BarDataSet(entries, "Produits");
barDataSet.setBarBorderWidth(0.9f);
barDataSet.setColors(ColorTemplate.COLORFUL_COLORS);
BarData barData = new BarData(barDataSet);
XAxis xAxis = barChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
IndexAxisValueFormatter formatter = new IndexAxisValueFormatter(months);
xAxis.setGranularity(1f);
xAxis.setValueFormatter(formatter);
barChart.setData(barData);
barChart.setFitBars(true);
barChart.animateY(5000);
barChart.invalidate();
One more thing, if I when to clear chart data and make others by a button which code I need to use.
Related
I have searched a lot and could not found any suitable solution for my requirement. While loading data for the first time the bar width is OK , but for large amount of data the bar width gets reduced, I did many changes on that but nothing worked. I have attached the code and pics below.and legend is not working while set Axis data on bar chart any help?
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonObjectRequest jsOnbjRequest = new
JsonObjectRequest(Request.Method.POST,
Constants.GETPICCHART, pieObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
final ArrayList<BarEntry> yEntrys = new ArrayList<>();
Log.d("pieData",response.toString());
try {
JSONArray jsonarray = (JSONArray) response.get("piechartlist");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String messageSent = jsonobject.getString("messageSent").trim();
String failed = jsonobject.getString("failed").trim();
String rejected = jsonobject.getString("rejected").trim();
String expired = jsonobject.getString("expired").trim();
String unDelivered = jsonobject.getString("unDelivered");
String delivered = jsonobject.getString("delivered");
String ndnc = jsonobject.getString("ndnc");
yEntrys.add(new BarEntry(Float.parseFloat(messageSent),Integer.parseInt(messageSent)));
yEntrys.add(new BarEntry(Float.parseFloat(failed),Integer.parseInt(failed)));
yEntrys.add(new BarEntry(Float.parseFloat(rejected),Integer.parseInt(rejected)));
yEntrys.add(new BarEntry(Float.parseFloat(expired),Integer.parseInt(expired)));
yEntrys.add(new BarEntry(Float.parseFloat(unDelivered),Integer.parseInt(unDelivered)));
yEntrys.add(new BarEntry(Float.parseFloat(delivered),Integer.parseInt(delivered)));
yEntrys.add(new BarEntry(Float.parseFloat(ndnc),Integer.parseInt(ndnc)));
}
} catch (JSONException e) {
e.printStackTrace();
}
BarDataSet set1;
set1 = new BarDataSet(yEntrys,"");
set1.setBarBorderWidth(1f);
set1.setDrawIcons(false);
ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
dataSets.add(set1);
ArrayList<Integer> colors = new ArrayList<Integer>();
colors.add(ContextCompat.getColor(getContext(),R.color.massage_Sent));
colors.add(ContextCompat.getColor(getContext(),R.color.failed));
colors.add(ContextCompat.getColor(getContext(),R.color.rejected));
colors.add(ContextCompat.getColor(getContext(),R.color.expiered));
colors.add(ContextCompat.getColor(getContext(),R.color.undelivred));
colors.add(ContextCompat.getColor(getContext(),R.color.delivered));
colors.add(ContextCompat.getColor(getContext(),R.color.ndnc));
set1.setColors(colors);
mBarChart.setExtraBottomOffset(1);
BarData data = new BarData(dataSets);
data.setBarWidth(0.9f);
data.setValueFormatter(new MyValueFormatter());
XAxis xAxis = mBarChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setLabelRotationAngle(30);
xAxis.setSpaceMax(5f);
xAxis.setGranularity(1f);
xAxis.setDrawGridLines(false);
xAxis.setGranularityEnabled(true);
Legend l=mBarChart.getLegend();
LegendEntry l1=new LegendEntry("messageSent", Legend.LegendForm.DEFAULT,10f,2f,null,ContextCompat.getColor(getContext(),R.color.massage_Sent));
LegendEntry l2=new LegendEntry("Failed", Legend.LegendForm.DEFAULT,10f,2f,null, ContextCompat.getColor(getContext(),R.color.failed));
LegendEntry l3=new LegendEntry("Rejected", Legend.LegendForm.DEFAULT,10f,1f,null,ContextCompat.getColor(getContext(),R.color.rejected));
LegendEntry l4=new LegendEntry("Expired", Legend.LegendForm.DEFAULT,10f,2f,null, ContextCompat.getColor(getContext(),R.color.expiered));
LegendEntry l5=new LegendEntry("Undelivred", Legend.LegendForm.DEFAULT,10f,2f,null, ContextCompat.getColor(getContext(),R.color.undelivred));
LegendEntry l6=new LegendEntry("Delivered", Legend.LegendForm.DEFAULT,10f,1f,null,ContextCompat.getColor(getContext(),R.color.delivered));
LegendEntry l7=new LegendEntry("NNDNC", Legend.LegendForm.DEFAULT,10f,1f,null,ContextCompat.getColor(getContext(),R.color.ndnc));
mBarChart.setFitBars(true);
l.setEnabled(true);
l.setWordWrapEnabled(true);
l.setCustom(new LegendEntry[]{l1,l2,l3,l4,l5,l6,l7});
mBarChart.setData(data);
mBarChart.invalidate();
After below line:
mBarChart.setData(data);
Add:
mBarChart.setVisibleXRange(1,3);
Where you can replace 1 as minimum number of values shown and 3 as maximum number of values shown on your chart. Above line will show 3 values at a time for next values you have to scroll chart. By default mpandroid charts try to cover all values in viewport and when you keep on adding entries on runtime your bars becomes thin to adjust. Once you add above line your chart will show maximum values as you described so it can b seen easily.
It seems that you need to modify your viewport. You can find a documentation in here
First you have to ensure that the Bars doesn't crumple inside the set Viewport and can be scrolled if there are more datas in the yEntrys ArrayList.
To do that you have to set the maximum and minimum visible range. Say you want to see 5 bars at a time. This value can be set according to your preference of how much wide you want the bars to be.
mBarChart.setVisibleXRangeMaximum(5);//no more than 5 values on the x-axis can be viewed at once without scrolling
mBarChart.setVisibleXRangeMinimum(5);//it is not possible to zoom in further than 5 values on the x-axis
This way you can ensure that the Bar width remains almost same, whatever may be the datas.
Code Edited -
final ArrayList<BarEntry> yEntrys = new ArrayList<>();
Log.d("pieData",response.toString());
try {
JSONArray jsonarray = (JSONArray) response.get("piechartlist");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
//...
yEntrys.add(new BarEntry(Float.parseFloat(messageSent),Integer.parseInt(messageSent)));
yEntrys.add(new BarEntry(Float.parseFloat(failed),Integer.parseInt(failed)));
yEntrys.add(new BarEntry(Float.parseFloat(rejected),Integer.parseInt(rejected)));
yEntrys.add(new BarEntry(Float.parseFloat(expired),Integer.parseInt(expired)));
yEntrys.add(new BarEntry(Float.parseFloat(unDelivered),Integer.parseInt(unDelivered)));
yEntrys.add(new BarEntry(Float.parseFloat(delivered),Integer.parseInt(delivered)));
yEntrys.add(new BarEntry(Float.parseFloat(ndnc),Integer.parseInt(ndnc)));
}
} catch (JSONException e) {
e.printStackTrace();
}
BarDataSet set1;
set1 = new BarDataSet(yEntrys,"");
//...
set1.setColors(colors);
mBarChart.setExtraBottomOffset(1);
BarData data = new BarData(dataSets);
//data.setBarWidth(0.9f);//This line is irrelevant now.
//mBarChart.setFitBars(true);//Irrelevant. Also can remove this line
mBarChart.setData(data);
//Add these two lines after setting the data
mBarChart.setVisibleXRangeMaximum(5);
mBarChart.setVisibleXRangeMinimum(5);
When there are 5 datas-
When there are more that 100 datas-
I am using MPAndroid Chart library to draw BarChart.
But not getting how to draw bars with real time data in on button click.
Can anyone please help me in this.
Thanks.
After getting data store that in List(graphData). Then,
BarChart barChart;
/*List to store real time data*/
private List<Integer> graphData = new ArrayList<>();
/*List of String which contains X-axis values */
ArrayList<String> xAxisValuesList = new ArrayList<>();
// create BarEntry for group
ArrayList<BarEntry> group = new ArrayList<>();
for (int i = 0; i < graphData.size(); i++) {
Log.d(TAG, "generating for:" + graphData.get(i));
group.add(new BarEntry(graphData.get(i), i));
}
// creating dataset for group
BarDataSet barDataSet = new BarDataSet(group, "Label");
// combined all dataset into an arraylist
ArrayList<BarDataSet> dataSets = new ArrayList<>();
dataSets.add(barDataSet);
// initialize the Bardata with argument labels and dataSet
BarData barData = new BarData(xAxisValuesList, dataSets);
barChart.setData(barData);
I have a problem with BarChart.. I have a 7 item on list. For example
final int[] a = {5,2,10,4,7,8,13};
final String[] b= {"January","February","March","April","May","June","Jully"};
So I want to show by pieces on Barchart. For example first 5 items show and when I click the button than 2 items remaining show in Barchart. Images is,
Than I want when I click the "WAFAW" button barchart is,
But my code working is,
So it means dont show the bar..How can I do that? Thanks for now..
My Code is,
final BarChart barChart = (BarChart) findViewById(R.id.chart);
Button button = (Button) findViewById(R.id.button);
final int[] a = {5,2,10,4,7,8,13};
final String[] b= {"January","February","March","April","May","June","Jully"};
final ArrayList<BarEntry> entries = new ArrayList<>();
final ArrayList<String> labels = new ArrayList<String>();
for(int i=0 ; i<5;i++){
entries.add(new BarEntry(a[i],i));
labels.add(b[i]);
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
entries.clear();
labels.clear();
for(int i=5; i<a.length;i++){
entries.add(new BarEntry(a[i],i));
labels.add(b[i]);
}
BarDataSet dataset = new BarDataSet(entries, "# of Calls");
barChart.getXAxis().setPosition(XAxis.XAxisPosition.TOP);
BarData data = new BarData(labels, dataset);
dataset.setColors(ColorTemplate.COLORFUL_COLORS);
barChart.setData(data);
barChart.animateY(3000);
}
});
BarDataSet dataset = new BarDataSet(entries, "# of Calls");
barChart.getXAxis().setPosition(XAxis.XAxisPosition.TOP);
BarData data = new BarData(labels, dataset);
dataset.setColors(ColorTemplate.COLORFUL_COLORS);
barChart.setData(data);
barChart.animateY(3000);
As far as I know there is no simple solution on how to select which bars to display. It depends on how dynamically you want/need to solve it.
The best solution I can think of would be keeing an array of bars to show like:
final int[] show_arr = {0,1,2,3,4,5};
and when onClick() is called you change the array to
final int[] show_arr = {5,7};
and then you run through the whole plotting routine again.
But you add the entries with looping through show_arr
I know this is not a super nice solution, but at least you only have to code the vector hard and can reuse all the other parts.
You can use below code for the same :
https://github.com/blackfizz/EazeGraph
https://github.com/HackPlan/AndroidCharts
I created a Piechart with MPandroidchart for my app. The chart works great. The problem is that the original data contains 4 data entry but the chart only show 3. Can somebody help? What is the limitation for this?
My PieChart
Hi Thank you so much for getting me back. The xVals and yVals are from SQLite database. xVals{30-,30-45,46-60,60-} String and yVals(6,14,13,3) float.
My codes are posted here:
private void AddDataCYNewCustomersAge(){
DataBaseHelper databasehelper = new DataBaseHelper (NewCustomerReportCurrentYear.this);
PieChart ageChart = new PieChart(this);
ageChart = (PieChart)findViewById(R.id.agechart);
//get yVals and datasets of marriage chart
ArrayList<Entry> yValsageCounts = new ArrayList<Entry>();
for(int i = 0;i < databasehelper.yDataIncomeCounts().size(); i++)
yValsageCounts.add(new Entry(databasehelper.yDataAgeCounts().get(i), i));
//get xVals of marriage chart
ArrayList<String> xValsage = new ArrayList<String>();
for(int i = 0;i < databasehelper.xDataAge().size();i++)
xValsage.add(databasehelper.xDataAge().get(i));
PieDataSet ageCounts = new PieDataSet(yValsageCounts, "");
//set yvals attribute
ageCounts.setSliceSpace(3);
ageCounts.setSelectionShift(5);
//add many colors
ageCounts.setColors(new int[]{R.color.Fuchsia, R.color.Aqua,R.color.Yellow,R.color.LightSeaGreen,R.color.Blue}, this);
// configue pie chart
ageChart.setUsePercentValues(true);
ageChart.setRotationEnabled(true);
ageChart.setRotationAngle(0);
ageChart.setDescriptionPosition(350, 550);
ageChart.setDrawHoleEnabled(true);
ageChart.setHoleColor(Color.TRANSPARENT);
ageChart.setHoleRadius(13);
ageChart.setTransparentCircleRadius(18);
ageChart.getLegend().setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
//ageChart.getLegend().setXEntrySpace(3);
// ageChart.getLegend().setYEntrySpace(3);
ageChart.getLegend().setTextColor(Color.BLUE);
ageChart.setDescription("Income");
ageChart.setDescriptionTextSize(13);
ageChart.setDescriptionColor(Color.BLUE);
//get income chart data
PieData ageData = new PieData(xValsage,ageCounts);
ageData.setValueFormatter(new PercentFormatter());
ageData.setValueTextSize(11);
ageData.setValueTextColor(Color.BLUE);
ageChart.setData(ageData);
//refresh data
ageChart.invalidate();
}
In my android application, I am new to graphs and using MPchart library to draw the graphs. I'm displaying the graph using string array on both - X axis and Y axis.
For x axis I created it successfully but for Y axis I need to convert my ArrayList<String> to BarData array list. I don't know how to do convert it. Can anyone tell me how to achieve this?
For X axis:
private ArrayList<String> getXAxis() {
ArrayList<String> xAxis = new ArrayList<>();
xAxis = new ArrayList<String>(Arrays.asList(bar_graph_names)); //converting string to arraylist
return xAxis;
}
For Y axis plotting values:
private ArrayList<BarDataSet> getData() {
ArrayList<String> yAxis_conv = new ArrayList<>();
yAxis_conv = new ArrayList<String>(Arrays.asList(bar_graph_values));
ArrayList<BarDataSet> yAxis_Datasets=null;
ArrayList<BarEntry> yAxis = new ArrayList<>();
for(int i = 0; i < bar_graph_values.length; i++)
{
BarEntry [] barentry = new BarEntry[bar_graph_values.length];
barentry[i] = new BarEntry(Float.valueOf(yAxis_conv.get(i)),i);
}
BarDataSet barDataSet1 = new BarDataSet(yAxis_conv , "");//Error occurring line
barDataSet1.setColors(ColorTemplate.COLORFUL_COLORS);
yAxis_Datasets = new ArrayList<>();
yAxis_Datasets.add(barDataSet1);
return yAxis_Datasets;
}
BarData object (which you give to the chart View) consist of one List representing x-values and one or more BarDataSet objects representing y-values data. BarDataSet object has String name and List of y-values.
Your structure of this objects is simply wrong. (for starters yAxis_conv is List<String>, where BarDataSet requires List<BarEntry>). There's more mistakes, but i'm not gonna point them out, just have some working code below:
private void setData() {
ArrayList<String> xVals = new ArrayList<String>();
ArrayList<BarEntry> yVals = new ArrayList<BarEntry>();
xVals = new ArrayList<String>(Arrays.asList(bar_graph_names));
for(int i=0; i < bar_graph_values.length; i++) {
BarEntry entry = new BarEntry(Float.valueOf(bar_graph_values[i]), i);
yVals.add(entry);
}
BarDataSet newSet = new BarDataSet(yVals, "DataSet");
BarData data = new BarData(xVals, newSet);
mChart.setData(data);
}