MPAndroidChart BarChart (Grouped DataSets) not showing all bars - java

I am using MPAndroidChart BarChart (Grouped DataSets) for showing data of two users. It is showing data but the problem is that its not displaying data on x-axis from start due to which all the bars are not visible.
Arrays:
String[] title_list = {"Whatsapp", "Visit", "Callback", "Interested"}
int[] title_values_1 = {50, 15, 25, 36};
int[] title_values_2 = {70, 35, 15, 10};
BarChart:
public void LoadBarChart()
{
List<BarEntry> barEntries1 = new ArrayList<>();
for (int i = 0; i < title_list.length; i++) {
barEntries1.add(new BarEntry(i, title_values_1[i]));
}
List<BarEntry> barEntries2 = new ArrayList<>();
for (int i = 0; i < title_list.length; i++) {
barEntries2.add(new BarEntry(i, title_values_2[i]));
}
BarDataSet dataSet1 = new BarDataSet(barEntries1, "Dataset 1");
dataSet1.setColors(getColor(R.color.pie_chart_blue));
dataSet1.setValueTextSize(10f); /* values size */
dataSet1.setValueTextColor(Color.WHITE);
BarDataSet dataSet2 = new BarDataSet(barEntries2, "Dataset 2");
dataSet2.setColors(getColor(R.color.pie_chart_red));
dataSet2.setValueTextSize(10f); /* values size */
dataSet2.setValueTextColor(Color.WHITE);
float groupSpace = 0.06f;
float barSpace = 0.02f; // x2 dataset
float barWidth = 0.45f; // x2 dataset
BarData data = new BarData(dataSet1, dataSet2);
ValueFormatter vf = new ValueFormatter() {
#Override
public String getFormattedValue(float value) { return ""+(int)value; }
};
data.setValueFormatter(vf);
data.setValueTextSize(12f);
data.setBarWidth(barWidth);
XAxis xAxis = barChart.getXAxis();
xAxis.setValueFormatter(new ValueFormatter() {
#Override
public String getFormattedValue(float value) {
return title_list[(int) value];
}
});
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setDrawGridLines(false);
xAxis.setDrawAxisLine(false);
xAxis.setLabelCount(title_list.length);
barChart.setData(data);
barChart.groupBars(0f, groupSpace, barSpace);
barChart.getDescription().setEnabled(false);
barChart.setDrawValueAboveBar(false);
barChart.setTouchEnabled(false);
barChart.animateY(1000);
barChart.invalidate();
}
I have tried answers on stackoverflow but nothing resolved my issue. Kindly help!
UPDATE:
After Shayan answer all bars are now visible but labels are not centered.
Is it possible to center the lables with the bars?

You have to play with the spacings, I think when its unable to adjust the whole thing in the screen it starts cutting bars.
Add this line so bars may start from the begining
xAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
Setting spacing and widths a bit low like this
float groupSpace = 0.06f;
float barSpace = 0.02f; // x2 dataset
float barWidth = 0.40f; // x2 dataset
The complete method will look something like this
public void LoadBarChart()
{
List<BarEntry> barEntries1 = new ArrayList<>();
for (int i = 0; i < title_list.length; i++) {
barEntries1.add(new BarEntry(i, title_values_1[i]));
}
List<BarEntry> barEntries2 = new ArrayList<>();
for (int i = 0; i < title_list.length; i++) {
barEntries2.add(new BarEntry(i, title_values_2[i]));
}
BarDataSet dataSet1 = new BarDataSet(barEntries1, "Dataset 1");
dataSet1.setColors(R.color.colorPrimary);
dataSet1.setValueTextSize(10f); /* values size */
dataSet1.setValueTextColor(Color.WHITE);
BarDataSet dataSet2 = new BarDataSet(barEntries2, "Dataset 2");
dataSet2.setColors(R.color.colorPrimary);
dataSet2.setValueTextSize(10f); /* values size */
dataSet2.setValueTextColor(Color.WHITE);
float groupSpace = 0.06f;
float barSpace = 0.02f; // x2 dataset
float barWidth = 0.40f; // x2 dataset
BarData data = new BarData(dataSet1, dataSet2);
ValueFormatter vf = new ValueFormatter() {
#Override
public String getFormattedValue(float value) { return ""+(int)value; }
};
data.setValueFormatter(vf);
// data.setValueTextSize(12f);
data.setBarWidth(barWidth);
XAxis xAxis = barChart.getXAxis();
xAxis.setValueFormatter(new ValueFormatter() {
#Override
public String getFormattedValue(float value) {
return title_list[(int) value];
}
});
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setDrawGridLines(false);
xAxis.setDrawAxisLine(false);
xAxis.setLabelCount(title_list.length);
xAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
barChart.setData(data);
barChart.groupBars(0f,groupSpace,barSpace);
barChart.getDescription().setEnabled(false);
barChart.setDrawValueAboveBar(false);
barChart.setTouchEnabled(false);
barChart.animateY(1000);
barChart.invalidate();
}
Hope this works!

I am able to achieve the desired result by the guidance of Shayan. I have added few attributes in the answer.
Spacing and Bar Width:
float groupSpace = 0.15f;
float barSpace = 0.01f; // x2 dataset
float barWidth = 0.42f; // x2 dataset
Addition at X-Axis:
xAxis.setAxisMinimum(0f);
xAxis.setGranularity(1);
xAxis.setCenterAxisLabels(true);
xAxis.setAxisMaximum(title_list.length);
Formatter:
barChart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(title_list));
So bar chart method now looks like this:
public void LoadBarChart()
{
List<BarEntry> barEntries1 = new ArrayList<>();
for (int i = 0; i < title_list.length; i++) {
barEntries1.add(new BarEntry(i, title_values_1[i]));
}
List<BarEntry> barEntries2 = new ArrayList<>();
for (int i = 0; i < title_list.length; i++) {
barEntries2.add(new BarEntry(i, title_values_2[i]));
}
BarDataSet dataSet1 = new BarDataSet(barEntries1, Global.employeesComparisonList.get(0).getName());
dataSet1.setColors(getColor(R.color.blue));
dataSet1.setValueTextSize(10f); /* values size */
dataSet1.setValueTextColor(Color.WHITE);
BarDataSet dataSet2 = new BarDataSet(barEntries2, Global.employeesComparisonList.get(1).getName());
dataSet2.setColors(getColor(R.color.red));
dataSet2.setValueTextSize(10f); /* values size */
dataSet2.setValueTextColor(Color.WHITE);
float groupSpace = 0.15f;
float barSpace = 0.01f; // x2 dataset
float barWidth = 0.42f; // x2 dataset
BarData data = new BarData(dataSet1, dataSet2);
ValueFormatter vf = new ValueFormatter() {
#Override
public String getFormattedValue(float value) { return ""+(int)value; }
};
data.setValueFormatter(vf);
data.setValueTextSize(12f);
data.setBarWidth(barWidth);
XAxis xAxis = barChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setDrawGridLines(false);
xAxis.setDrawAxisLine(false);
xAxis.setLabelCount(title_list.length);
xAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
xAxis.setGranularity(1);
xAxis.setCenterAxisLabels(true);
xAxis.setAxisMaximum(title_list.length);
Legend l = barChart.getLegend();
l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
barChart.setData(data);
barChart.groupBars(0f,groupSpace,barSpace);
barChart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(title_list));
barChart.getDescription().setEnabled(false);
barChart.setDrawValueAboveBar(false);
barChart.setTouchEnabled(false);
barChart.animateY(1000);
barChart.invalidate();
}
Final Result:

Yes, that can be done quite easily.
What you need is a BarChart with multiple BarDataSets where each set (in your case) represents count of each activity.
Here is an example of how to create a BarChart with multiple DataSets
Here is an tutorial of how to use MPAndroidChart with Realm.io
Example code (without realm.io)
List<String> xValues = ...; // "Denmark", "Finland", ...
XAxis xAxis = chart.getXAxis();
xAxis.setValueFormatter(new MyValueFormatter(xValues));
xAxis.setCenterAxisLabels(true);
// create 2 datasets
BarDataSet set1 = new BarDataSet(valuesMen, "Men");
set1.setColor(Color.BLUE);
BarDataSet set2 = new BarDataSet(valuesWomen, "Women");
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 need further assistance, here is a detailed tutorial on grouped BarChart available on the wiki.
If you want to "stack" values in a BarChart above each other, you need to create a stacked-barchart: Android Stacked Bars Chart
**
Result Image
**

Related

MPAndroidChart BarChart - Vertical values inside of bars

I am using the MPAndroidChart library for the bar chart, In that, I have used chart.setDrawValueAboveBar(false) to set bar values inside of bars, now I want to display the values vertically inside of bars.
Please help..Thank you in advance.
first make this false
mChart.setDrawValueAboveBar(false);
then enable draw values for your data set
barDataSet.setDrawValues(true);
Since you need to rotate the text as well.. you have to implement a custom renderer for your chart. If you want to know how renderer works, check this answer
I have provided a sample implementation below. You can modify it to control the position of the text as it suits you.
Custom Renderer
public class BarChartCustomRenderer extends BarChartRenderer {
public BarChartCustomRenderer(BarDataProvider chart, ChartAnimator animator, ViewPortHandler viewPortHandler) {
super(chart, animator, viewPortHandler);
}
public void drawValue(Canvas c, IValueFormatter formatter, float value, Entry entry, int dataSetIndex, float x, float y, int color) {
mValuePaint.setColor(color);
c.save();
c.rotate(90f, x, y);
Log.d("here", formatter.getFormattedValue(value, entry, dataSetIndex, mViewPortHandler) );
c.drawText(formatter.getFormattedValue(value, entry, dataSetIndex, mViewPortHandler), x, y, mValuePaint);
c.restore();
}
}
Chart Code
BarChart mChart = (BarChart) findViewById(R.id.barChart);
mChart.setDrawBarShadow(false);
mChart.setDrawValueAboveBar(false);
mChart.getDescription().setEnabled(false);
mChart.setDrawGridBackground(false);
//**add renderer**
BarChartCustomRenderer barChartCustomRenderer = new BarChartCustomRenderer(mChart, mChart.getAnimator(), mChart.getViewPortHandler());
mChart.setRenderer(barChartCustomRenderer);
XAxis xaxis = mChart.getXAxis();
xaxis.setDrawGridLines(false);
xaxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xaxis.setGranularity(0.5f);
xaxis.setGranularityEnabled(true);
xaxis.setDrawLabels(true);
xaxis.setDrawAxisLine(false);
YAxis yAxisLeft = mChart.getAxisLeft();
yAxisLeft.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
yAxisLeft.setDrawGridLines(false);
yAxisLeft.setDrawAxisLine(false);
yAxisLeft.setEnabled(false);
mChart.getAxisRight().setEnabled(false);
Legend legend = mChart.getLegend();
legend.setEnabled(false);
ArrayList<BarEntry> valueSet1 = new ArrayList<BarEntry>();
ArrayList<String> ylabels = new ArrayList<>();
for (int i = 0; i < 6; ++i) {
BarEntry entry = new BarEntry(i, (i + 1) * 2);
valueSet1.add(entry);
ylabels.add(" " + i);
}
List<IBarDataSet> dataSets = new ArrayList<>();
BarDataSet barDataSet = new BarDataSet(valueSet1, " ");
barDataSet.setColor(Color.CYAN);
barDataSet.setDrawValues(true);
dataSets.add(barDataSet);
BarData data = new BarData(dataSets);
data.setBarWidth(0.4f);
data.setValueTextSize(10f);
data.setValueTextColor(Color.BLACK);
mChart.setData(data);
mChart.setFitBars(true);
mChart.invalidate();
Result
class MyCustomRenderer(
chart: BarDataProvider, animator: ChartAnimator, viewPortHandler: ViewPortHandler
) : HorizontalBarChartRenderer(chart, animator, viewPortHandler) {
override fun drawValue(c: Canvas, valueText: String, x: Float, y: Float, color: Int) {
mValuePaint.color = color
val xPoint = Utils.convertDpToPixel(26f)
val yPoint = Utils.convertDpToPixel(16f)
c.drawText(valueText, xPoint , yPoint , mValuePaint)
}
}

Sprites array merges the when rendering sprites

Sprite bucketImage, background, r1, r2, r5,
r10, r20, r50, r100, r200, r500, k1, k2, k5, k10, k20, k50;
I create objects in the method called spawnRaindrop(). I have an array of sprites and I want to sprites were changed in the cycle as it is now, it works, but the images are merged with each other.
sprites = new Sprite[15];
r1 = new Sprite(atlas.findRegion("r1"));
r1.flip(false, true);
r2 = new Sprite(atlas.findRegion("r2"));
r2.flip(false, true);
r5 = new Sprite(atlas.findRegion("r5"));
r5.flip(false, true);
r10 = new Sprite(atlas.findRegion("r10"));
r10.flip(false, true);
r20 = new Sprite(atlas.findRegion("r20"));
r20.flip(false, true);
r50 = new Sprite(atlas.findRegion("r50"));
r50.flip(false, true);
r100 = new Sprite(atlas.findRegion("r100"));
r100.flip(false, true);
r200 = new Sprite(atlas.findRegion("r200"));
r200.flip(false, true);
r500 = new Sprite(atlas.findRegion("r500"));
r500.flip(false, true);
k1 = new Sprite(atlas.findRegion("k1"));
k1.flip(false, true);
k2 = new Sprite(atlas.findRegion("k2"));
k2.flip(false, true);
k5 = new Sprite(atlas.findRegion("k5"));
k5.flip(false, true);
k10 = new Sprite(atlas.findRegion("k10"));
k10.flip(false, true);
k20 = new Sprite(atlas.findRegion("k20"));
k20.flip(false, true);
k50 = new Sprite(atlas.findRegion("k50"));
k50.flip(false, true);
sprites[0] = r1;
sprites[1] = r2;
sprites[2] = r5;
sprites[3] = r10;
sprites[4] = r20;
sprites[5] = r50;
sprites[6] = r100;
sprites[7] = r200;
sprites[8] = r500;
sprites[9] = k1;
sprites[10] = k2;
sprites[11] = k5;
sprites[12] = k10;
sprites[13] = k20;
sprites[14] = k50;
Create game object
private void spawnRaindrop() {
Rectangle raindrop = new Rectangle();
raindrop.x = MathUtils.random(0, 800 - 100);
raindrop.y = 480;
raindrop.width = 100;
raindrop.height = 100;
raindrops.add(raindrop);
lastDropTime = TimeUtils.nanoTime();
}
Create and draw array sprite
game.batch.draw(bucketImage, bucket.x, bucket.y);
for (Rectangle raindrop : raindrops) {
for (int i = 0; i < sprites.length - 1; i++) {
game.batch.draw(sprites[i], raindrop.x, raindrop.y);
}
}
game.batch.end();
RESULT:
I attached the picture, and it can be seen that the images accumulate on each other
It looks like your problem is that you are using the same raindrop.x and raindrop.y coordinates for all sprites!
for (Rectangle raindrop : raindrops)
{
for (int i = 0; i < sprites.length - 1; i++)
{
// The following will draw ALL sprites at the same location!
game.batch.draw(sprites[i], raindrop.x, raindrop.y);
}
}
What you can try is to create a new class called (for example): Raindrops and then in this class maintain a single x,y coordinate for each individual image:
class Raindrop
{
Vector2 coordinates;
Sprite sprite;
}
Then in your spawnRaindrop method, create an array of these Raindrop's and an individual (random?) image for each.
EDIT: I wrote the following code directly here without testing anything, so it will most likely have some errors, but nothing you shouldn't be able to fix yourself...
// This goes into your initialisation method
String regions[] = {"r1", "r2", "r5", "r10", "etc etc etc"}
Raindrop raindrops[] = new Raindrop[15];
for ( int i = 0; i < raindrops.length; i++ )
{
raindrop[i] = new Raindrop();
raindrop[i].coordinate.x = MathUtils.random(screenWidth);
raindrop[i].coordinate.y = MathUtils.random(screenHeight);
raindrop[i].sprite = atlas.findRegion(regions[(int)MathUtils.random(regions.length)]);
}
Then your main loop should look something like this:
game.batch.draw(bucketImage, bucket.x, bucket.y);
for ( Raindrop raindrop : raindrops )
{
game.batch.draw(raindrop.sprite, raindrop.coordinate.x, raindrop.coordinate.y);
}
game.batch.end();

Flat line instead wave

I want to plot a sine wave, but instead my application generates a flat line. When I use series with random from jchartfree example everything works fine. I also use debugger to check if values are good. Values are different than zero
public void createDataset() {
XYSeriesCollection dataset = new XYSeriesCollection();
XYSeries series1 = new XYSeries("Object 1");
double A = 1;
double T = 1;
double Fs = 10;
double f = 200;
int rozmiar = (int) (T*Fs);
double[] x = new double[rozmiar];
for (int i = 0; i < rozmiar; i++)
{
x[i] = A * Math.sin(2 * Math.PI * f * i / Fs);
series1.add(i, x[i]);
}
dataset.addSeries(series1);
data = dataset;
}
//...
public void createChartPanel() {
//pWykres = new JPanel();
//if(java.util.Arrays.asList(getComponents()).contains(pWykres)){
//getContentPane().remove(pWykres);
//}
if(pWykres != null){
pWykres.removeAll();
pWykres.revalidate();
}
String chartTitle = "Objects Movement Chart";
String xAxisLabel = "X";
String yAxisLabel = "Y";
JFreeChart chart = ChartFactory.createXYLineChart(chartTitle,
xAxisLabel, yAxisLabel, dataset);
customizeChart(chart);
pWykres = new ChartPanel(chart);
getContentPane().add(pWykres, BorderLayout.CENTER);
setSize(620, 460);
//validate();
pWykres.repaint();
}
//endregion
//...
//region
private void customizeChart(JFreeChart chart) {
XYPlot plot = chart.getXYPlot();
XYSplineRenderer renderer;
renderer = new XYSplineRenderer();
renderer.setSeriesShapesVisible(0, false);
// sets paint color for each series
renderer.setSeriesPaint(0, Color.RED);
// sets thickness for series (using strokes)
renderer.setSeriesStroke(0, new BasicStroke(1.0f));
// sets paint color for plot outlines
//plot.setOutlinePaint(Color.BLUE);
//plot.setOutlineStroke(new BasicStroke(2.0f));
// sets renderer for lines
plot.setRenderer(renderer);
// sets plot background
plot.setBackgroundPaint(Color.WHITE);
// sets paint color for the grid lines
plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.BLACK);
plot.setDomainGridlinesVisible(true);
plot.setDomainGridlinePaint(Color.BLACK);
}
You are taking the sine of values that are always whole multiples of 2 * PI, so all of these values will be (approximately) zero, hence your graph will end up appearing flat unless it is scaled to show up these tiny values (which are just floating point errors).
x[i] = A * Math.sin(2 * Math.PI * f * i / Fs);
where A = 1 and f/Fs = 20 and i is integer
For example:
Math.sin(0) // 0.0
Math.sin(2 * Math.PI) // -2.4492935982947064E-16 (approximately zero)
Math.sin(4 * Math.PI) // -4.898587196589413E-16 (approximately zero)
To see the characteristic shape of a sine wave, you need to vary the input to the sin function by much smaller increments, e.g. pi/10 or less.

create bar chart by accessing data from 2 .csv files

.csv file 1 data:
sampler_label,aggregate_report_count,average,aggregate_report_median,aggregate_report_90%_line
HTTP Request1, 750 ,26339 ,22644 , 40210
HTTP Request2, 750 ,8280 ,4781 ,21016
.csv file 2 data:
sampler_label,aggregate_report_count,average,aggregate_report_median,aggregate_report_90%_line
HTTP Request1, 350 ,2539 ,2224 , 48410
HTTP Request4, 350 ,8736 ,9285 ,38217
I want to display bar graph, which should depict values of average from both files for each sampler label.
Here there are 2 average values in each file. there may be n number of values. in bar graph i want to display values of file 1 and file 2 in one graph only.
Please help me....
public JFreeChart createBarChartFromCSV() {
csv csvReader = new csv();
List<String[]> csvData1 = null;
List<String[]> csvData2 = null;
int indexOfAverage1 = 0;
int indexOfAverage2 = 0;
csvData1 = csvReader.getDataFromCSV1(csv.CSVFILENAME1);
csvData2 = csvReader.getDataFromCSV2(csv.CSVFILENAME2);
for(String[] columnArray : csvData1)
for(int i = 0; i< columnArray.length; i++)
if(columnArray[i].equalsIgnoreCase("average")){
enter code here
indexOfAverage1 = i;
break;
}
if(indexOfAverage1 == 0){
System.err.println("Error retrieving data from CSV File1 !!");
System.exit(0);
}
for(String[] columnArray : csvData2)
for(int j = 0; j< columnArray.length; j++)
if(columnArray[j].equalsIgnoreCase("average")){
indexOfAverage2 = j;
break;
}
if(indexOfAverage2 == 0){
System.err.println("Error retrieving data from CSV File2 !!");
System.exit(0);
}
JFreeChart barChart = generateBarChart(csvData1,csvData2, indexOfAverage1,indexOfAverage2);
return barChart;
}
private JFreeChart generateBarChart(List<String[]> csvData1,List<String[]> csvData2, int columnIndex1, int columnIndex2){
DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
final String YAXIS_NAME = csvData1.get(0)[columnIndex1]; //value returned is "average"
final String XAXIS_NAME = csvData1.get(0)[0]; //value returned is "sampler_label"
for(int i = 1; i < csvData1.size() - 1; i++){
long averageValue1 = Long.parseLong(csvData1.get(i)[columnIndex1]);
String columnKey1 = csvData1.get(i)[0];
dataSet.setValue(averageValue1, YAXIS_NAME, columnKey1); // plot the graph
}
for(int j = 1; j< csvData2.size() - 1; j++){
long averageValue2 = Long.parseLong(csvData2.get(j)[columnIndex2]);
String columnKey2 = csvData2.get(j)[0];
dataSet.setValue(averageValue2, YAXIS_NAME, columnKey2); // plot the graph
}
System.out.println("created");
JFreeChart chart = ChartFactory.createBarChart("Comparison between the average of 2 values", XAXIS_NAME, YAXIS_NAME, dataSet, PlotOrientation.VERTICAL, true, true, false);
final CategoryPlot plot = chart.getCategoryPlot();
chart.setBackgroundPaint(Color.white);
plot.setBackgroundPaint(Color.lightGray);
plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinePaint(Color.white);
BarRenderer renderer=new BarRenderer();
System.out.print( "set the range axis to display integers only...");
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
System.out.print( "disable bar outlines...");
renderer = (BarRenderer) plot.getRenderer();
renderer.setDrawBarOutline(false);
renderer.setMaximumBarWidth(0.10);
System.out.print( "set up gradient paints for series...");
final GradientPaint gp0 = new GradientPaint(
0.0f, 0.0f, Color.blue,
0.0f, 0.0f, Color.lightGray
);
final GradientPaint gp1 = new GradientPaint(
0.0f, 0.0f, Color.green,
0.0f, 0.0f, Color.lightGray
);
renderer.setSeriesPaint(0, gp0);
renderer.setSeriesPaint(1, gp1);
return chart;
}

JFreeChart - CategoryAxis step

I have a method for generating dataset:
private CategoryDataset createDataset(double[] arr,
String seriesName) {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for (int i = 0; i < arr.length; i++) {
dataset.addValue(arr[i], "mySeries", new Integer(i));
}
return dataset;
}
and create BarChart:
JFreeChart chart = ChartFactory.createBarChart(chartTitle,
xaxis, // domain axis label
yaxis, // range axis label
dataset, // data
orientation, // orientation
true, // include legend
true, // tooltips?
false // URLs?
);
Array of doubles hold histogram data, so there are 255 values.
When I display chart there are labels for
all values from 0 - 255 on x axis. I want display only labels for several indexes (for example: 0, 10, 20, 30). I saw that in RangeAxis there is setStandardTickUnits method. But in CategoryAxis:
CategoryAxis domainAxis = plot.getDomainAxis();
I didn't find this.
Any help?
You can try as follows,
NumberAxis vn = (NumberAxis) plot.getRangeAxis();
vn.setTickUnit(new NumberTickUnit(10d));
vn.setRange(0D, Math.ceil(factor * MAX_VALUE));
--that is you just need cast plot.getRangeAxis() to NumberAxis type.
I had same problem. I created new class implementing 'Comparable', and use it as last parameter in addValue(...). You can create something like
class MyCategory implements Comparable<MyCategory> {
Integer value;
String stValue;
MyCategory(int val) {
value = val;
stValue = val%10==0?""+val:"";}
public int compareTo(MyCategory key) { return value.compareTo(key.value); }
public String toString() { return stValue; }
}
And then instead of
dataset.addValue(arr[i], "mySeries", new Integer(i));
use
dataset.addValue(arr[i], "mySeries", new MyCategory(i));

Categories