Hi I am trying to create a bar chart using MPAndroidChart library in Android Studio for my java application. I have managed to plot a bar chart using single integer values, but I would like to plot double values.
Here is my code for plotting single integer values
public class walk extends AppCompatActivity {
HorizontalBarChart barChart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_walk);
barChart = (HorizontalBarChart) findViewById(R.id.bargraph);
ArrayList<BarEntry> barEntries = new ArrayList<>();
barEntries.add(new BarEntry(10f,0));
barEntries.add(new BarEntry(5f,1));
BarDataSet barDataSet = new BarDataSet(barEntries,"ACTIVITIES");
ArrayList <String> pa = new ArrayList<>();
pa.add("WALKING");
pa.add("RUNNING");
BarData theData = new BarData(pa,barDataSet);
barChart.setData(theData);
barDataSet.setBarSpacePercent(70f);
}
I would like to plot the following values 20.333333333333332 and 2.0071271275749623.
I would appreciate any help I could get, apologies if anything is unclear I am new to this site.
Converting double to float before plotting :
double point1 = 20.333333333333332;
double point2 = 2.0071271275749623;
float fp1 = (float)point1;
float fp2 = (float)point2;
ArrayList<BarEntry> barEntries = new ArrayList<>();
barEntries.add(new BarEntry(fp1,0));
barEntries.add(new BarEntry(fp2,1));
BarDataSet barDataSet = new BarDataSet(barEntries,"ACTIVITIES");
Related
I have requirement to show a XyLineChart with adding data dynamically. I have used the chart Customizer to read data from db with some additional logic and adding that to chart. But I am not able to create tool tip on mouse over for each data points on chart. following is my code for Customizer.
What is the correct way to create Tool tip on Mouse over?
public class MyChartCustomizer extends JRAbstractChartCustomizer{
#Override
public void customize(JFreeChart chart, JRChart jrChart) {
XyPlot plot= chart.getXyPlot;
XYSeriesCollection ds = (XYSeriesCollection) plot.getDataset();
XYSeries x1 = new XYSeries("C 1", true, true);
x1.add(10,20);
XYBarRenderer ren = (XYBarRenderer) plot.getRenderer();
plot.setRenderer(ren);
ren.setSeriesToolTipGenerator(0, new XYToolTipGenerator() {
#Override
public String generateToolTip(XYDataset arg0, int arg1, int arg2) {
return "C 1";
}
});
ren.setToolTipGenerator(new XYToolTipGenerator() {
#Override
public String generateToolTip(XYDataset arg0, int arg1, int arg2) {
return "C 1";
}
});
chart.fireChartChanged();
}
}
}
Thank you, Petter and Trashgod helping me out to find the solution for this issue.
The actual issue is, if we add the new data using customizer then the new data point get display on the graph but respected tool tip does not get generated and the map used for tooltip will not be updated on html code. Since I have to use jasper server as per requirement I implemented following work around other way will be simply generate chart image with map using jfreechart API and display on the jsp page(no need for report design....)..
Following is the way I Implemented this.
I used the following code to generate the same chart which jasperserver/jasper studio create the chart. this gives me same chart which internally get created and I create the map for tooltips and passing it as parameter to browser and using javascript function inserting the new map html code with the chart image.
XYSeriesCollection xyDataSet = new XYSeriesCollection();
JFreeChart chart = ChartFactory.createXYLineChart(
cur_chart.getTitle(),
cur_chart.getxLabel(), cur_chart.getyLabel(),
xyDataSet,
PlotOrientation.VERTICAL,
true,
true,
false);
String chartId = null;
for ( Object tt : chart.getSubtitles()){
if (tt instanceof TextTitle){
chartId= ((TextTitle) tt).getText();
}
}
XYPlot plot = chart.getXYPlot();
//following code to set font size and color is required so that same chart with matching tooltip pixels can we generated.
LegendItemCollection legends = plot.getLegendItems();
List<JRSeriesColor> colors = new ArrayList<JRSeriesColor>();
System.out.println("Customizer: "+ chartId);
NumberAxis xAxis = (NumberAxis) plot.getDomainAxis();
NumberAxis yAxis = (NumberAxis) plot.getRangeAxis();
xAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
yAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
Color trans = new Color(0xFF, 0xFF, 0xFF, 0);
chart.setBackgroundPaint(trans);
plot .setBackgroundPaint(trans);
chart.getLegend().setBackgroundPaint(trans);
chart.setTitle(cur_chart.getTitle());
Font font3 = new Font("Dialog", Font.PLAIN, 10);
plot.getDomainAxis().setLabelFont(font3);
plot.getRangeAxis().setLabelFont(font3);
plot.getDomainAxis().setLabelPaint(Color.BLACK);
plot.getRangeAxis().setLabelPaint(Color.BLACK);
//some more code to add real time data to XyDataset,
ToolTipTagFragmentGenerator tooltipConstructor = new ToolTipTagFragmentGenerator() {
public String generateToolTipFragment(String arg0) {
String toolTip = " title = \"" + arg0.replace("\"", "") + "\"";
return (toolTip);
}
};
URLTagFragmentGenerator urlConstructor = new URLTagFragmentGenerator() {
public String generateURLFragment(String arg0) {
String address = " href=\"ControllerAddress\\methodName?"
+ arg0.replace("\"", "") + "\"";
return (address);
}
};
ChartRenderingInfo info = new ChartRenderingInfo(
new StandardEntityCollection());
// BufferedImage bi chart.createBufferedImage(272, 178, info);
TextTitle tt = new TextTitle("chart1");
tt.setFont(font3);
chart.addSubtitle(tt);
ChartUtilities.saveChartAsPNG(new File("/tmp/test.png"), chart, 500, 250, info);
String map = ChartUtilities.getImageMap(cur_chart.getName(), info, tooltipConstructor, urlConstructor);
github.PhilJay:MPAndroidChart:v2.0.9`
I was wondering if I can add star icons and numbers as XAxisValues like image below?
I've already added the numbers and it's working fine but I don't know how to add star icons! Is there a way to combine text and icons?
Here is my code so far:
private ArrayList<BarDataSet> getDataSet(int stars1, int stars2, int stars3, int stars4, int stars5) {
ArrayList<BarDataSet> dataSets = null;
ArrayList<BarEntry> valueSet1 = new ArrayList<>();
BarEntry v1e1 = new BarEntry(stars5, 4);
valueSet1.add(v1e1);
BarEntry v1e2 = new BarEntry(stars4, 3);
valueSet1.add(v1e2);
BarEntry v1e3 = new BarEntry(stars3, 2);
valueSet1.add(v1e3);
BarEntry v1e4 = new BarEntry(stars2, 1);
valueSet1.add(v1e4);
BarEntry v1e5 = new BarEntry(stars1, 0);
valueSet1.add(v1e5);
BarDataSet barDataSet1 = new BarDataSet(valueSet1, "");
barDataSet1.setColors(new int[]{getResources().getColor(R.color.chart5), getResources().getColor(R.color.chart4),
getResources().getColor(R.color.chart3), getResources().getColor(R.color.chart2), getResources().getColor(R.color.chart1)});
barDataSet1.setValueTextSize(9);
dataSets = new ArrayList<>();
dataSets.add(barDataSet1);
return dataSets;
}
private ArrayList<String> getXAxisValues() {
ArrayList<String> xAxis = new ArrayList<>();
xAxis.add("1");
xAxis.add("2");
xAxis.add("3");
xAxis.add("4");
xAxis.add("5");
return xAxis;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
BarData data = new BarData(getXAxisValues(), getDataSet(stars1, stars2, stars3, stars4, stars5));
barChart.setData(data);
barChart.setDescription("");
barChart.invalidate();
barChart.getXAxis().setDrawGridLines(false);
barChart.getXAxis().setDrawAxisLine(false);
barChart.setDrawGridBackground(false);
barChart.getAxisLeft().setDrawGridLines(false);
barChart.getAxisRight().setDrawGridLines(false);
barChart.getAxisLeft().setDrawAxisLine(false);
barChart.getAxisRight().setDrawAxisLine(false);
barChart.getLegend().setEnabled(false);
barChart.getXAxis().setDrawLabels(true);
barChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
barChart.getAxisRight().setDrawLabels(false);
barChart.getAxisLeft().setDrawLabels(false);
}
Thanks for your time... ♥
Just use ★ character and it will be displayed well. You can use x axis value formatter for formatting values:
barChart.getXAxis().setValueFormatter(new IAxisValueFormatter() {
#Override
public String getFormattedValue(float value, AxisBase axis) {
return "value ★";
}
}
Here is result :
I'm using MPAndroidChart to build BarChart, but I can't set my BarDataSet(1) and set my column's content(2) to vertical. Can anyone help?
public void LoadChart(final ArrayList<String> nameDate, ArrayList<Float> fl){
com.github.mikephil.charting.charts.BarChart chart = (com.github.mikephil.charting.charts.BarChart) findViewById(R.id.barchart);
/* final String[] nameDate={"JAN","FEB","MAR","APR","MAY","JUN"};
Float[] fl = new Float[]{30f,80f,60f,50f,70f,60f};*/
List<BarEntry> entries = new ArrayList<>();
for(int i=0;i<fl.size();i++)
{
entries.add(new BarEntry(i, fl.get(i)));
}
mDB.open();
BarDataSet set = new BarDataSet(entries, "BarDataSet");
set.setColor(Color.rgb(103,203,27));
BarData data = new BarData(set);
data.setBarWidth(0.9f); // set custom bar width
chart.setData(data);
chart.setFitBars(true); // make the x-axis fit exactly all bars
chart.animateXY(2000, 2000);
chart.setScaleEnabled(false);
chart.invalidate(); // refresh
Description description = chart.getDescription();
description.setEnabled(false);
XAxis xAxis = chart.getXAxis();
xAxis.setDrawGridLines(false);
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setDrawGridLines(false);
xAxis.setGranularity(1f);
xAxis.setValueFormatter(new IAxisValueFormatter() {
#Override
public String getFormattedValue(float value, AxisBase axis) {
return nameDate.get((int) value);
}
});
YAxis yLabels = chart.getAxisLeft();
yLabels.setDrawGridLines(false);
YAxis yLabels1 = chart.getAxisRight();
yLabels1.setEnabled(false);
}
Yes, is possible, just using following code:
mChart.setDescription(""); // Hide the description
mChart.getAxisLeft().setDrawLabels(false);
mChart.getAxisRight().setDrawLabels(false);
mChart.getXAxis().setDrawLabels(false);
mChart.getLegend().setEnabled(false);
try this
OR
pieChart.setUsePercentValues(true);
pieChart.getDescription().setEnabled(false);
pieChart.setExtraOffsets(0, 0, 0,0 );
pieChart.setDragDecelerationFrictionCoef(0.95f);
mChart.setCenterTextTypeface(mTfLight);
mChart.setCenterText(generateCenterSpannableText());
pieChart.setDrawHoleEnabled(false);
// mChart.setHoleColor(Color.WHITE);
// mChart.setTransparentCircleColor(Color.WHITE);
// mChart.setTransparentCircleAlpha(110);
// mChart.setHoleRadius(58f);
// mChart.setTransparentCircleRadius(61f);
pieChart.setDrawCenterText(false);
pieChart.setRotationAngle(0);
// enable rotation of the chart by touch
pieChart.setRotationEnabled(false);
pieChart.setHighlightPerTapEnabled(false);
// mChart.setUnit(" €");
// mChart.setDrawUnitsInChart(true);
// add a selection listener
pieChart.setOnChartValueSelectedListener(this);
setData(4, 100);
pieChart.animateY(0, Easing.EasingOption.EaseInOutQuad);
// mChart.spin(2000, 0, 360);
// mSeekBarX.setOnSeekBarChangeListener(this);
// mSeekBarY.setOnSeekBarChangeListener(this);
Legend l = pieChart.getLegend();
l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
l.setOrientation(Legend.LegendOrientation.VERTICAL);
l.setDrawInside(false);
l.setXEntrySpace(7f);
l.setYEntrySpace(0f);
l.setYOffset(0f);
// mChart.setDescription(""); // Hide the description
// mChart.getAxisLeft().setDrawLabels(false);
// mChart.getAxisRight().setDrawLabels(false);
// mChart.getXAxis().setDrawLabels(false);
pieChart.getLegend().setEnabled(false); // Hi
// entry label styling
pieChart.setEntryLabelColor(Color.WHITE);
// mChart.setEntryLabelTypeface(mTfRegular);
pieChart.setEntryLabelTextSize(12f);
return rootView;
and try this code bar data set is not visible again
I have a HorizontalBarChart from MPAndroidChart library (version v3.0.0-beta1) in which I display the monthly spending of the user's accounts.
So i implemented this method:
List<Account> accounts = getAccounts();
final ArrayList<BarEntry> entries = new ArrayList<>();
Float count = 0F;
for (Account account : accounts) {
entries.add(new BarEntry(count++, new float[]{Float.valueOf(account.getBalance())}, account.getName()));
}
BarDataSet dataset = new BarDataSet(entries, " ");
dataset.setColors(ColorTemplate.PASTEL_COLORS);
dataset.setValueTextSize(10F);
BarData data = new BarData(dataset);
horizontalBarChartMonthlySpending.setData(data);
horizontalBarChartMonthlySpending.setDescription("Gastos por conta neste mês!");
horizontalBarChartMonthlySpending.getAxisLeft().setDrawLabels(false);
horizontalBarChartMonthlySpending.getAxisRight().setDrawLabels(false);
horizontalBarChartMonthlySpending.setFitBars(true);
horizontalBarChartMonthlySpending.setTouchEnabled(false);
And this is what i got:
What i want is, beside every bar, put the description of the related account. I tried to do this in line 6 with the account.getName() but it didn't appear anywhere in the report.
Is there a way to do it?
I had this problem and correct putting this code:
horizontalBarChartMonthlySpending.getXAxis().setValueFormatter(new AxisValueFormatter() {
#Override
public String getFormattedValue(float value, AxisBase axis) {
return entries.get((int) value).getData().toString();
}
#Override
public int getDecimalDigits() {
return 0;
}
});
XAxis xAxis = horizontalBarChartMonthlySpending.getXAxis();
xAxis.setGranularity(1f);
xAxis.setGranularityEnabled(true);
Actually im trying this:
public static DefaultCategoryDataset dataset = new DefaultCategoryDataset();;
public void atualizaDataset(int humano, int zumbi, int rodada){
final String series1 = "Humano";
final String series2 = "Zumbi";
dataset.addValue(humano, series1, (Comparable)rodada);
dataset.addValue(zumbi, series2, (Comparable)rodada);
}
and in the main
public Grafico g = new Grafico("Grafico");
public void verGrafico(){
g.atualizaDataset(qtdHumanos, qtdZumbis, nroJogada);
g.pack();
g.setVisible(true);
g.repaint();
}
but when i send the values to ´atualizaDataset´ he add them to the graphic but do not save this dataset to concatenate with the new values that are coming..