Aligning x-axis labels with Bars in MpAndroidChart BarChart in Android - java

I would like to align the labels of my x-axis with the bars in my bar chart.
When launching the graph, only 3 of the 5 labels appear, as can be seen in this image .
As soon as I zoom in slightly, the rest of the labels appear, as can be seen in this image
The following is the relevant code relating to the building of the Bar Graph and its x-axis:
for (int c = 0; c < numberOfStoriesPlayed; c++) {
barEntries.add(new BarEntry(chartData [0] [c], chartData [1] [c]));
}
BarDataSet barDataSet = new BarDataSet(barEntries, "Social Stories");
XAxis xAxis = barChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setCenterAxisLabels(true);
xAxis.setDrawGridLines(false);
xAxis.setValueFormatter(new IndexAxisValueFormatter(xAxisLabel));
BarData data;
data = new BarData(barDataSet);
barChart.setData(data);
barChart.getAxisRight().setDrawLabels(false);
barChart.getAxisLeft().setDrawLabels(false);
barChart.getAxisLeft().setDrawGridLines(false);
barChart.getAxisRight().setDrawGridLines(false);
barChart.setTouchEnabled(true);
barChart.setDragEnabled(true);
barChart.setScaleEnabled(true);
barChart.setDrawGridBackground(false);
barChart.notifyDataSetChanged();
barChart.invalidate();
barChart.setAutoScaleMinMaxEnabled(true);
I would like to find a way for all labels to show up immediately, and not just when I start zooming, and also for them to be properly aligned with the bars in the graph. Thanks in advance!

Related

How to draw grouped bar chart in Android with different number of columns in each group?

This is the chart that I want to create (click on the link to view image):
Desired chart
I have researched a lot about Grouped Bar Chart in MPAndroidChart but that library seems to restrict. Each group must have the same number of columns and the column order must be consistent. Does anyone know how to create a grouped bar chart like in my image using MPAndroidChart (or any other libraries)?
Please help me. Thank you in advance.
Could you try this code?
List<String> xValues = ...; // "Shop1", "Shop2", "Shop3"
XAxis xAxis = chart.getXAxis();
xAxis.setValueFormatter(new MyValueFormatter(xValues));
// create 2 datasets
BarDataSet set1 = new BarDataSet(valuesProduct1, "Product1"); //valuesProduct1 are the values corresponding to the shops,
set1.setColor(Color.BLUE);
BarDataSet set2 = new BarDataSet(valuesProduct2, "Product2");
set2.setColor(Color.RED);
BarData data = new BarData(set1, set2);
chart.setData(data);
chart.groupBars(...); // available since release v3.0.0
chart.invalidate(); // refresh
If you have some troubles where the shop has no products, just put zero on the concrete position

MPChart xAxis values not aligned

I am trying to implement grouped MPAndroid Bar chart. I have a group of 2 datasets that i want to display. The problem is that the xaxis values are not center aligned with the bar chart (as per the screenshot). I checked other questions as well and implemented the following answers provided.
I want to make the labels center aligned with the grouped bars.
float barSpace = 0.02f;
float groupSpace = 0.3f;
int groupCount = 2;
data.setBarWidth(0.155f);
pvaAmount_chart.getXAxis().setAxisMinimum(0);
pvaAmount_chart.getXAxis().setAxisMaximum(0 + pvaAmount_chart.getBarData().getGroupWidth(groupSpace, barSpace) * groupCount);
pvaAmount_chart.groupBars(0, groupSpace, barSpace);
pvaAmount_chart.getXAxis().setCenterAxisLabels(true);
pvaAmount_chart.notifyDataSetChanged();
When entering groupcount=2 as 2 types of bars:
When entering groupcount=4 number of grouped charts:
i'm doing it like this :
String [] values = new String[insert the lenght of your array]
for (int blabla=0;i<values[lenght];blabla++){
String dayOfTheWeek = dateFormat.format(mydate);
vales[blabla] = dayOfTheWeek //in my case
}
xAxis.setGranularity(1.0f); //
xAxis.setCenterAxisLabels(false);
xAxis.setGranularityEnabled(true);
xAxis.setLabelCount(values.length,false); //
List<String> stringList = new ArrayList<String>(Arrays.asList(values));
xAxis.setGranularityEnabled(true);
xAxis.setLabelCount(values.length,false); //
xAxis.setValueFormatter(new IndexAxisValueFormatter(getXAxisValues((ArrayList<String>) stringList)));
i'm using : 'com.github.PhilJay:MPAndroidChart:v3.1.0'

JFreeChart: Bar chart X axis labels overlapping with large datasets

I'm facing the below issue while using JFreeChart for creating bar chart with relatively large dataset:
Bar chart generated with overlapping X-axis labels. I have tried positioning the labels vertical, still no help. Please provide the best possible way to solve this issue. Code snipped below:
CategoryDataset categoryDataSet = getBarDataset();
JFreeChart barChart = ChartFactory.createBarChart("TITLE", "X-LABEL","Y-LABEL", categoryDataSet, PlotOrientation.VERTICAL, true, true, false);
barChart.getCategoryPlot().getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_90);
barChart.getCategoryPlot().getDomainAxis().setMaximumCategoryLabelLines(4);
jpg = Image.getInstance(im, null);
document.add(jpg);
Update:
As per the suggestion from #trashgod, I've used SlidingCategoryDataset indexing from 0 to the column count. When the column count is large(50 here), the X-Label's are overlapping. When the column count is set to a lower number, it's working fine. I want to find a solution for large column size. Importantly, I need to export the chart image to pdf. Please help me in arriving to a feasible solution. Thanks!
private static void createBarChart() throws DocumentException, IOException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FILE_LOCN));
writer.setStrictImageSequence(true);
document.open();
CategoryDataset categoryDataset = createDataset();
int colCount = categoryDataset.getColumnCount();
SlidingCategoryDataset slidingCategoryDataSet = new SlidingCategoryDataset(categoryDataset, 0, colCount);
JFreeChart barChart = ChartFactory.createBarChart("TITLE", "X-LABEL","Y-LABEL", slidingCategoryDataSet,
PlotOrientation.VERTICAL, true, true, false);
barChart.getCategoryPlot().getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_90);
barChart.getCategoryPlot().getDomainAxis().setMaximumCategoryLabelLines(4);
java.awt.Image im = barChart.createBufferedImage(400, 400);
Image jpg = Image.getInstance(im, null);
jpg.scaleToFit(400, 400);
document.add(jpg);
document.close();
writer.close();
}
private static CategoryDataset createDataset() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for (int i = 0; i <= 50; i++) {
dataset.addValue(i, "R", "C" + i);
}
return dataset;
}
With a large number of categories, specifying vertical labels via setCategoryLabelPositions() is a good choice for maximizing legibility. Arbitrary CategoryLabelPositions are supported.
In an interactive chart, SlidingCategoryDataset, mentioned here, allows your application to set the count and starting index of visible categories as desired, perhaps using a slider or spinner, as shown here.
How can I achieve this in a PDF?…More pixels seems a good idea, but how can we implement that here?
In a fixed size context with a given number of categories, you can optimize the size of the chart image via createBufferedImage(), as shown here, or Image.scaleToFit(). For yet larger datasets, it may be possible to create multiple linked charts in a domain specific way, e.g. by year or subsidiary.

Combining a BarChart and Linechart with J free chart

Hi im trying to create a chart that is a combination of a bar chart and a line chart in JFree chart. The bar chart is vs time and for each hour it will compare two (or more) different values.
The line chart uses the same scale as the bar chart and shows the overall trend of the data set.
You can plot each dataset on the same Plot, and use a different renderer for each dataset (for instance a BarRenderer and LineAndShapeRenderer). Below is a simplified example that generates some mock data values (1-9) and renders the same data as both bars and lines on the same ChartPanel.
//Mock data
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
int[] times = new int[]{1,2,3,4,5,6,7,8,9};
for ( int i = 0; i < times.length; i++ ){
dataset.addValue(times[i], "Time", "Hour" + String.valueOf(i+1));
}
//create the plot
CategoryPlot plot = new CategoryPlot();
//add the first dataset, and render as bar values
CategoryItemRenderer renderer = new BarRenderer();
plot.setDataset(0,dataset);
plot.setRenderer(0,renderer);
//add the second dataset, render as lines
CategoryItemRenderer renderer2 = new LineAndShapeRenderer();
plot.setDataset(1, dataset);
plot.setRenderer(1, renderer2);
//set axis
plot.setDomainAxis(new CategoryAxis("Time"));
plot.setRangeAxis(new NumberAxis("Value"));
And the resulting Chart:

JfreeChart - How to hide item from legend - Problem of colors

I would like to hide items from legend in Jfreechart and I've tried this code
jFreeChart: How to hide items from legend?
It works but something strange happened : the colors of the legend items do not match to the right data anymore. In other words, in the graph, a piece of data appears in yellow for example but the legend corresponding to this item appears in another color. In fact, the colors in the legend have been mixed.
Besides, when I try to display both old and new legends, there is no problem of colors but when I make the old legend invisible, the problem of mixed color appears. Obviously, I would like not to display the old legend.
Working code =>
LegendItemCollection legendItemsOld = localCombinedDomainXYPlot.getLegendItems();
final LegendItemCollection legendItemsNew = new LegendItemCollection();
for(int i = 0; i<4; i++){
legendItemsNew.add(legendItemsOld.get(i));
}
LegendItemSource source = new LegendItemSource() {
LegendItemCollection lic = new LegendItemCollection();
{lic.addAll(legendItemsNew);}
public LegendItemCollection getLegendItems() {
return lic;
}
};
localJFreeChart.addLegend(new LegendTitle(source));
ChartUtilities.applyCurrentTheme(localJFreeChart);
localJFreeChart.getLegend().setVisible(true); ///////////////////
Not working code =>
LegendItemCollection legendItemsOld = localCombinedDomainXYPlot.getLegendItems();
final LegendItemCollection legendItemsNew = new LegendItemCollection();
for(int i = 0; i<4; i++){
legendItemsNew.add(legendItemsOld.get(i));
}
LegendItemSource source = new LegendItemSource() {
LegendItemCollection lic = new LegendItemCollection();
{lic.addAll(legendItemsNew);}
public LegendItemCollection getLegendItems() {
return lic;
}
};
localJFreeChart.addLegend(new LegendTitle(source));
ChartUtilities.applyCurrentTheme(localJFreeChart);
localJFreeChart.getLegend().setVisible(false); ///////////////////
Based on this thread, you might try adding a null element to replace the unwanted legend item. The other approach appears to elide unwanted items, but I'm not sure if you're doing the same. To clarify, consider posting an sscce that demonstrates the problem. One of the org.jfree.chart.demo classes may be a suitable starting point.

Categories

Resources