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);
}
Related
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.
I need to get all bars but I am getting single bar (last array).Even the logic is right.I don't know please help me.Thanks in advance.I search in google but I didn't got answer.
Below is main part of full code
Initialize
String empName[];
int converted[], notconverted[], notcontacted[];
Here I made Json parsing the data coming from the server
for (int i = 0; i < employees_array.length(); i++) {
empName = new String[employees_array.length()];
converted = new int[employees_array.length()];
notconverted = new int[employees_array.length()];
notcontacted = new int[employees_array.length()];
JSONObject empData = employees_array.getJSONObject(i);
empName[i] = empData.getString("EmployeeName");
empName[i].replace("-?\\d+.\\d+", " ");
if (empData.has("ConvertedActionCount")) {
converted[i] = employees_array.getJSONObject(i).getInt("ConvertedActionCount");
}
if (empData.has("NotConvertedActionCount")) {
notconverted[i] = employees_array.getJSONObject(i).getInt("NotConvertedActionCount");
}
if (empData.has("NotContactedActionCount")) {
notcontacted[i] = employees_array.getJSONObject(i).getInt("NotContactedActionCount");
}
Log.d("arraysize", converted[i] + "");
function_EMPChart(empArraysize, empName, converted,
notconverted, notcontacted);
I am passing values to function Emp chart method
private void function_EMPChart(int empArraysize, String[] s, int[]
converted, int[] notconverted, int[] notcontacted) {
XAxis xl = msc_managerDashboard_empStats.getXAxis();
xl.setPosition(XAxis.XAxisPosition.BOTTOM);
xl.setDrawAxisLine(true);
xl.setDrawGridLines(false);
xl.setGranularity(10f);
YAxis yl = msc_managerDashboard_empStats.getAxisLeft();
yl.setDrawAxisLine(true);
yl.setDrawGridLines(true);
yl.setAxisMinimum(0f); // this replaces setStartAtZero(true)
YAxis yr = msc_managerDashboard_empStats.getAxisRight();
yr.setDrawAxisLine(true);
yr.setDrawGridLines(false);
yr.setAxisMinimum(0f);
ArrayList<BarEntry> yVals = new ArrayList<BarEntry>();
ArrayList<String> xVals = new ArrayList<>();
xVals = new ArrayList<String>(Arrays.asList(s));
msc_managerDashboard_empStats.setFitBars(true);
for (int j = 0; j < s.length; j++) {
Log.d("checklength", j + "");
int value1 = converted[j];
int value2 = notconverted[j];
int value3 = notcontacted[j];
Log.d("getvalue", value1 + " " + value2 + " " + value3);
yVals.add(new BarEntry(j, new float[]{value1, value2, value3}));
yVals.add(new BarEntry(4, new float[]{10.0f, 20.0f, 30.0f}));
yVals.add(new BarEntry(5, new float[]{5.0f, 15.0f, 20.0f}));
Log.d("checky", yVals.add(new BarEntry(j, new float[]{converted[j], notconverted[j], notcontacted[j]})) + "");
}
BarDataSet set1 = new BarDataSet(yVals, "");
set1.setColors(getColors());
ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
dataSets.add(set1);
BarData data = new BarData(dataSets);
data.notifyDataChanged();
msc_managerDashboard_empStats.setData(data);
msc_managerDashboard_empStats.notifyDataSetChanged();
msc_managerDashboard_empStats.invalidate();
Log.d("yvalues", yVals + "");
msc_managerDashboard_empStats.setFitBars(true);
}
I guess you are using this library.
I don't really understand your code in what you try to accomplish (I see multiple bars per employee I guess).
At least what is wrong, you call setData within this for loop for (int i = 0; i < employees_array.length(); i++), which means you override the data every time.
You should create a list of BarDataSets in that for loop and set the data in the end.
Your main issue here is that you create a new set of data every time. If you keep the same set your code might also work. Define dataSets once in the beginning and keep adding your sets. I mean this line:
ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
dataSets.add(set1);
I guess you want to have a grouped bar chart which you can find here: https://github.com/PhilJay/MPAndroidChart/wiki/Setting-Data#grouped-barchart
Example:
YourData[] group1 = ...;
YourData[] group2 = ...;
List<BarEntry> entriesGroup1 = new ArrayList<>();
List<BarEntry> entriesGroup2 = new ArrayList<>();
// fill the lists
for(int i = 0; i < group1.length; i++) {
entriesGroup1.add(new BarEntry(i, group1.getValue()));
entriesGroup2.add(new BarEntry(i, group2.getValue()));
}
BarDataSet set1 = new BarDataSet(entriesGroup1, "Group 1");
BarDataSet set2 = new BarDataSet(entriesGroup2, "Group 2");
BarData data = new BarData(set1, set2);
data.setBarWidth(barWidth); // set the width of each bar
barChart.setData(data);
barChart.groupBars(1980f, groupSpace, barSpace); // perform the "explicit" grouping
barChart.invalidate(); // refresh
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);
got the following code:
Legend legend = mChart.getLegend();
legend.setLabels(new String[]{"aaaaa", "bbbbb", "ccccc"});
This setting does not take effect Is there an other way to set the text ?
I could not find the method setCustom(int[] color, String[] labels) in v3.0.0. Only setCustom(LegendEntry[]) for which you have to pass LegendEntry objects.
List<LegendEntry> entries = new ArrayList<>();
for (int i = 0; i < titleList.size(); i++) {
LegendEntry entry = new LegendEntry();
entry.formColor = colorList.get(i);
entry.label = titleList.get(i);
entries.add(entry);
}
legend.setCustom(entries);
You can set custom labels with colors:
First make sure Legend is enable. Unless enable legend.
legend.setEnabled(true);
With com.github.PhilJay:MPAndroidChart:v3.0.0:-
legend .setCustom(ColorTemplate.VORDIPLOM_COLORS, new String[] { "aaaaa", "bbbbb", "ccccc"});
setCustom(int[] colors, String[] labels): Sets a custom legend's labels and colors arrays. The colors count should match the labels count. Each color is for the form drawn at the same index.
Pass the label name as second parameter to constructor PieEntry().
(For version > 3.0.0)
Example:
ArrayList<PieEntry> yvalues = new ArrayList<PieEntry>();
yvalues.add(new PieEntry(8f, "JAN"));
yvalues.add(new PieEntry(15f, "FEB"));
yvalues.add(new PieEntry(12f, "MAR"));
yvalues.add(new PieEntry(25f, "APR"));
yvalues.add(new PieEntry(23f, "MAY"));
yvalues.add(new PieEntry(17f, "JUNE"));
PieDataSet dataSet = new PieDataSet(yvalues, "Election Results");
PieData data = new PieData();
data.addDataSet(dataSet);
data.setValueFormatter(new PercentFormatter());
pieChart.setData(data);
1)Add dependency to build.gradle app level
compile 'com.github.PhilJay:MPAndroidChart:v2.1.0'
2)make function chartData
private void chartData() {
ArrayList<Entry> entries = new ArrayList<>();
entries.add(new Entry(50, 0));
entries.add(new Entry(60, 1));
final int[] piecolors = new int[]{
Color.rgb(183, 28, 28),
Color.rgb(27, 94, 32)};
PieDataSet dataset = new PieDataSet(entries, "");
ArrayList<String> labels = new ArrayList<String>();
labels.add("Borrowing");
labels.add("Pending");
PieData data = new PieData(labels, dataset);
dataset.setColors(ColorTemplate.createColors(piecolors)); //
data.setValueTextColor(Color.WHITE);
pieChart.setDescription("Description");
pieChart.setData(data);
}
3)Call chartData() in onCreate()
Thanks to vikas singh and other hints elsewhere, here's how I solved both coloring for the piechart and legend, for MPAndroidChart v3.0.3:
private void visualizeAnalytics(ArrayList<Transaction> transactions) {
PieChart graph = rootView.findViewById(R.id.graph);
ArrayList<PieEntry> entries = new ArrayList<>();
HashMap<String, Integer> categoryFrequencyMap = new HashMap<>();
for(Transaction T: transactions) {
String category = T.getType().name();
if(categoryFrequencyMap.containsKey(category)){
categoryFrequencyMap.put(category, categoryFrequencyMap.get(category) + T.getAmount());
}else {
categoryFrequencyMap.put(category, T.getAmount());
}
}
ArrayList<String> categories = new ArrayList<>();
int e = 0;
for(String category: categoryFrequencyMap.keySet()){
categories.add(e, category);
entries.add(new PieEntry(categoryFrequencyMap.get(category), category));
e++;
}
PieDataSet categories_dataSet = new PieDataSet(entries, "Categories");
categories_dataSet.setSliceSpace(2f);
categories_dataSet.setValueTextSize(15f);
//categories_dataSet.setValueTextColor(Color.RED);/* this line not working */
graph.setEntryLabelColor(Color.RED);
categories_dataSet.setSelectionShift(10f);
categories_dataSet.setValueLinePart1OffsetPercentage(80.f);
categories_dataSet.setValueLinePart1Length(1f);
categories_dataSet.setValueLinePart2Length(0.9f);
categories_dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
PieData pieData = new PieData(categories_dataSet);
graph.setData(pieData);
Legend legend = graph.getLegend();
List<LegendEntry> legendEntries = new ArrayList<>();
RandomColor randomColor = new RandomColor();
int[] colors = randomColor.randomColor(categories.size());
for (int i = 0; i < categories.size(); i++) {
LegendEntry legendEntry = new LegendEntry();
legendEntry.formColor = colors[i];
legendEntry.label = categories.get(i);
legendEntries.add(legendEntry);
}
categories_dataSet.setColors(colors);
legend.setEnabled(false);
legend.setCustom(legendEntries);
Description description = new Description();
description.setText("Analyzing Transaction Vol by Category");
graph.setDescription(description);
graph.animateY(5000);
graph.invalidate(); // refresh
}
For the nice random colors, I sourced from this: https://github.com/lzyzsd/AndroidRandomColor
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();
}