I have created a pie and a line chart using Mpandroidchart.
Pie Chart
Code
getEntries();
pieDataSet = new PieDataSet(pieEntries, "");
pieDataSet.setColors(ColorTemplate.JOYFUL_COLORS);
pieDataSet.setSliceSpace(2f);
pieDataSet.setValueTextColor(Color.BLACK);
pieDataSet.setValueTextSize(10f);
pieDataSet.setSliceSpace(5f);
pieData = new PieData(pieDataSet);
pieChart.getDescription().setEnabled(false);
pieChart.getLegend().setEnabled(false);
pieChart.setCenterText("Last Two Months Sale" );
pieChart.setCenterTextSize(14f);
pieChart.setCenterTextColor(Color.BLUE);
pieChart.animateX(1500);
pieChart.setData(pieData);
public void getEntries() {
pieEntries = new ArrayList<>();
pieEntries.add(new PieEntry(200,"March", 0));
pieEntries.add(new PieEntry(300, "April",1));
}
Line Chart
Code
private ArrayList<Entry> lineChartDataSet(){
ArrayList<Entry> dataSet = new ArrayList<Entry>();
dataSet.add(new Entry(1,200));
dataSet.add(new Entry(2,300));
dataSet.add(new Entry(3,500));
return dataSet;
}
lineDataSet = new LineDataSet(lineChartDataSet(),"data set");
lineDataSet.setLineWidth(1.75f);
lineDataSet.setCircleRadius(5f);
lineDataSet.setCircleHoleRadius(2.5f);
iLineDataSets.add(lineDataSet);
lineData = new LineData(iLineDataSets);
lineChart.setNoDataText("Data not Available");
lineChart.getDescription().setEnabled(false);
lineChart.getLegend().setEnabled(false);
lineDataSet.setColors(color);
lineChart.setTouchEnabled(true);
lineChart.setDragEnabled(true);
lineDataSet.setCircleColor(Color.parseColor("#891e9a"));
lineDataSet.setCircleHoleColor(Color.parseColor("#891e9a"));
lineDataSet.setDrawHighlightIndicators(false);
lineDataSet.setDrawCircles(true);
lineDataSet.setDrawCircleHole(true);
lineDataSet.setLineWidth(5);
lineDataSet.setCircleRadius(5);
lineDataSet.setCircleHoleRadius(5);
lineDataSet.setValueTextSize(10);
lineDataSet.setValueTextColor(Color.BLACK);
lineChart.setPinchZoom(false);
lineChart.getAxisLeft().setSpaceTop(40);
lineChart.getAxisLeft().setSpaceBottom(40);
XAxis xAxis = lineChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setDrawGridLines(false);
xAxis.setValueFormatter(new IndexAxisValueFormatter(xAxisLabel));
xAxis.setGranularity(1f);
xAxis.setGranularityEnabled(true);
lineChart.getAxisRight().setEnabled(false);
lineChart.setData(lineData);
lineChart.invalidate();
Both the charts are displaying but I want to change the format of the value. In both the Pie and Line charts, one can only add floating values. But I want to add strings.
Example
I want to do the following
pieEntries.add(new PieEntry(200,"March", 0));
replace with
pieEntries.add(new PieEntry("200K","March", 0));
and
dataSet.add(new Entry(1,200));
replace with
dataSet.add(new Entry(1,"200K"));
How can I achieve it ?
Any help would be highly appreciated.
You can use ValueFormatter. Create ValueFormatter and then set it to the pieData
ValueFormatter formatter = new ValueFormatter() {
#Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
return ((int) value) + " " + "K";
}
};
pieData.setValueFormatter(formatter);
If you use LargeValueFormatter it automatically turn values like "1.000" into "1k", "1.000.000" into "1m" (million) e.g. To use LargeValueFormatter just set it to pieData.
pieData.setValueFormatter(new LargeValueFormatter())
See also https://github.com/PhilJay/MPAndroidChart/wiki/The-ValueFormatter-interface
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 am working with a project which is using MPAndroidChart library which makes me really crazy, I want to remove it.
The problem is I have created a custom ValueFormatter and I can't understand where these values come from, all are wrong.
private void setData() {
for (int i = 1; i <= 10; i++) {
Entry entry = new Entry(i, i);
values.add(entry);
}
IAxisValueFormatter valueFormatter = new myValueFormatter();
XAxis xAxis = mChart.getXAxis();
xAxis.setValueFormatter(valueFormatter);
LineDataSet set1 = new LineDataSet(values, "DataSet 1");
ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
dataSets.add(set1); // add the datasets
// create a data object with the datasets
LineData data = new LineData(dataSets);
// set data
mChart.setData(data);
}
custom formatter class:
I have an array which has 1,2,3,4,5,6,7,8,9,10 values
but I get 2,4,6,8,10 values in getFormattedValue method.
public classmyValueFormatter implements IAxisValueFormatter {
#Override
public String getFormattedValue(float value, AxisBase axis) {
System.out.println(value); //Here I get odd values where they come from I don't know.
}
}
Well, generally that's how library is written. Have a look here:
https://github.com/PhilJay/MPAndroidChart/blob/master/MPChartLib/src/main/java/com/github/mikephil/charting/renderer/XAxisRenderer.java#L205
String label = mXAxis.getValueFormatter().getFormattedValue(mXAxis.mEntries[i / 2], mXAxis);
Author's intention was probably to give more spacing between labels. If you think this is a bug, submit issue to library's repository on Github.
I am trying to display date and time on x-axis but its not get.also it returns x-axis as blank.
My Code:-
ArrayList<Entry> entries = new ArrayList<>();
entries.add(new Entry(1479249799770L, 98.3f));
entries.add(new Entry(1479249799771L, 58.3f));
entries.add(new Entry(1479249799772L, 78.3f));
entries.add(new Entry(1479249799773L, 48.3f));
entries.add(new Entry(1479249799774L, 68.3f));
LineDataSet set1;
// create a dataset and give it a type
set1 = new LineDataSet(entries, "DataSet 1");
set1.setFillAlpha(110);
set1.setColor(Color.BLACK);
set1.setCircleColor(Color.BLACK);
set1.setLineWidth(1f);
set1.setCircleRadius(3f);
set1.setDrawCircleHole(false);
set1.setValueTextSize(9f);
set1.setDrawFilled(false);
mChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
mChart.getXAxis().setValueFormatter(new MyXAxisValueFormatter());
mChart.setViewPortOffsets(60, 0, 50, 60);
//ArrayList<ILineDataSet> dataSets = new ArrayList<>();
//dataSets.add(set1);
//LineData data = new LineData(dataSets);
//LineDataSet set = new LineDataSet(null, null);
LineData data = new LineData();
data.addDataSet(set1);
mChart.setData(data);
also add MyAxisValueFormatter class for formatting x-axis values:-
public class MyXAxisValueFormatter implements IAxisValueFormatter {
#Override
public String getFormattedValue(float value, AxisBase axis) {
// Simple version. You should use a DateFormatter to specify how you want to textually represent your date.
Log.d("",""+value);
Date date = new Date((long) value);
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateString = formatter.format(date);
return dateString;
}
#Override
public int getDecimalDigits() {
return 0;
}
}
Thanks.Suggest me What i did anything wrong in above code?
These are my new entries x values i.e timestamp entries are wrong.
I tried below and get perfect graph.
entries.add(new Entry(1451660400L, 98.3f));
entries.add(new Entry(1451685600L, 58.3f));
entries.add(new Entry(1451721600L, 78.3f));
entries.add(new Entry(1451743200L, 48.3f));
entries.add(new Entry(1451761200L, 68.3f));
and also get x-values label as date.
Does anybody have an idea on how to make this: my app image look like this: how it should be?
My question is: how to make each line of the Horizontal Bar Chart fill between the two lines?
for (Iterator<Map.Entry<String, Float>> iterator = structuredData.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, Float> entry = iterator.next();
//i*10 => starting position of the bar
horizontalBarChartArr.add(new BarEntry((i*10), entry.getValue()));
names.add(entry.getKey());
i++;
}
XAxis xAxis = horizontalBarChart.getXAxis();
xAxis.setValueFormatter(new IAxisValueFormatter() {
#Override
public String getFormattedValue(float value, AxisBase axis) {
return names.get((int)value % names.size());
}
});
xAxis.setDrawGridLines(true);
xAxis.setDrawAxisLine(true);
BarDataSet barDataSet = new BarDataSet(horizontalBarChartArr, "Day Expenses");
barDataSet.setColors(Color.RED);
BarData data = new BarData(barDataSet);
data.setBarWidth(9f);
horizontalBarChart.setDoubleTapToZoomEnabled(false);
Description a = new Description();
a.setText("");
horizontalBarChart.setDescription(a);
horizontalBarChart.invalidate();
horizontalBarChart.animateY(1200);
horizontalBarChart.setData(data);
Check this example to your case:
https://github.com/ddanny/achartengine
It´s Automatically exported from code.google.com/p/achartengine
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