MPAndroidChart BarChart - Vertical values inside of bars - java

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)
}
}

Related

MPAndroidChart BarChart (Grouped DataSets) not showing all bars

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
**

Javafx 2.2: How to implement a new Chart that extends LineChart

I'm trying to implement a new chart which supports drawing minor grid lines. Earlier I tried implementing it by plotting lines JavaFx 2.x: How to draw minor grid lines. I would like to go the native route of drawing Path's instead of plotting lines.
I'm new to JavaFx and any help/guidance will be appreciated. The current code just concentrates on drawing minor horizontal grid lines.
public class CTChart extends LineChart
{
private final Path horizontalMinorGridLines = new Path();
public CTChart(final NumberAxis xAxis, final NumberAxis yAxis)
{
super(xAxis, yAxis);
this.setAnimated(false);
this.setCreateSymbols(false);
this.setAlternativeRowFillVisible(false);
this.setLegendVisible(false);
this.setHorizontalGridLinesVisible(true);
this.setVerticalGridLinesVisible(true);
getPlotChildren().add(horizontalMinorGridLines);
horizontalMinorGridLines.getStyleClass().setAll("chart-horizontal-minor-grid-lines");
int lowerBound = (int) yAxis.getLowerBound();
int upperBound = (int) yAxis.getUpperBound();
int tickUnit = (int) yAxis.getTickUnit();
int minorTickCount = yAxis.getMinorTickCount();
int minorTickUnit = tickUnit / minorTickCount;
horizontalMinorGridLines.getElements().clear();
for (int i = lowerBound; i < upperBound; i = i + minorTickUnit) {
ObservableList<TickMark<Number>> tickMarks = yAxis.getTickMarks();
for (TickMark<Number> tickMark : tickMarks) {
tickMark.getPosition();
// horizontalMinorGridLines.getElements().add(new MoveTo(zero, tickMark.getPosition()));
// horizontalMinorGridLines.getElements().add(new LineTo(zero + xAxis.getWidth(), tickMark.getPosition()));
}
}
}
}
Things I'm not able to figure out
Am I heading in the right direction?
How to get the X,Y coordinates for the MoveTo and LineTo API's?
How to render/which code renders the minor grid lines?
Should everything be in the constructor?
yourObject.setOnMouseMoved(event -> {
double x = event.getX();
double y = event.getY();
}
Example. Use this in CSS:
.chart-alternative-row-fill {
-fx-fill: transparent;
-fx-stroke: transparent;
-fx-stroke-width: 0;
}
Setting properties of the LineChart must be in constructor. Adding series does not have to be in constructor.

How can I can insert an image or stamp on a pdf where there is free space available like a density scanner

I have a pdf file where-in I am adding a stamp to all it's pages.
But, the problem is, the stamp is added to the upper-left corner of each page. If, the page has text in that part, the stamp appears on the text.
My question is, is there any method by which I can read each page and if there is no text in that part add the stamp else search for nearest available free space, just like what a density scanner does?
I am using IText and Java 1.7.
The free space fider class and the distance calculation function are the same that is there in the accepted answer.
Following is the edited code I am using:
// The resulting PDF file
String RESULT = "K:\\DCIN_TER\\DCIN_EPU2\\CIRCUIT FROM BRANCH\\RAINBOW ORDERS\\" + jtfSONo.getText().trim() + "\\PADR Release\\Final PADR Release 1.pdf";
// Create a reader
PdfReader reader = new PdfReader("K:\\DCIN_TER\\DCIN_EPU2\\CIRCUIT FROM BRANCH\\RAINBOW ORDERS\\" + jtfSONo.getText().trim() + "\\PADR Release\\Final PADR Release.pdf");
// Create a stamper
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
// Loop over the pages and add a footer to each page
int n = reader.getNumberOfPages();
for(int i = 1; i <= n; i++)
{
Collection<Rectangle2D> rectangles = find(reader, 300, 100, n, stamper); // minimum width & height of a rectangle
Iterator itr = rectangles.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
if(!(rectangles.isEmpty()) && (rectangles.size() != 0))
{
Rectangle2D best = null;
double bestDist = Double.MAX_VALUE;
Point2D.Double point = new Point2D.Double(200, 400);
float x = 0, y = 0;
for(Rectangle2D rectangle: rectangles)
{
double distance = distance(rectangle, point);
if(distance < bestDist)
{
best = rectangle;
bestDist = distance;
x = (float) best.getX();
y = (float) best.getY();
int left = (int) best.getMinX();
int right = (int) best.getMaxX();
int top = (int) best.getMaxY();
int bottom = (int) best.getMinY();
System.out.println("x : " + x);
System.out.println("y : " + y);
System.out.println("left : " + left);
System.out.println("right : " + right);
System.out.println("top : " + top);
System.out.println("bottom : " + bottom);
}
}
getFooterTable(i, n).writeSelectedRows(0, -1, x, y, stamper.getOverContent(i)); // 0, -1 indicates 1st row, 1st column upto last row and last column
}
else
getFooterTable(i, n).writeSelectedRows(0, -1, 94, 140, stamper.getOverContent(i)); // bottom left corner
}
// Close the stamper
stamper.close();
// Close the reader
reader.close();
public Collection<Rectangle2D> find(PdfReader reader, float minWidth, float minHeight, int page, PdfStamper stamper) throws IOException
{
Rectangle cropBox = reader.getCropBox(page);
Rectangle2D crop = new Rectangle2D.Float(cropBox.getLeft(), cropBox.getBottom(), cropBox.getWidth(), cropBox.getHeight());
FreeSpaceFinder finder = new FreeSpaceFinder(crop, minWidth, minHeight);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
parser.processContent(page, finder);
System.out.println("finder.freeSpaces : " + finder.freeSpaces);
return finder.freeSpaces;
}
// Create a table with page X of Y, #param x the page number, #param y the total number of pages, #return a table that can be used as footer
public static PdfPTable getFooterTable(int x, int y)
{
java.util.Date date = new java.util.Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");
String month = sdf.format(date);
System.out.println("Month : " + month);
PdfPTable table = new PdfPTable(1);
table.setTotalWidth(120);
table.setLockedWidth(true);
table.getDefaultCell().setFixedHeight(20);
table.getDefaultCell().setBorder(Rectangle.TOP);
table.getDefaultCell().setBorder(Rectangle.LEFT);
table.getDefaultCell().setBorder(Rectangle.RIGHT);
table.getDefaultCell().setBorderColorTop(BaseColor.BLUE);
table.getDefaultCell().setBorderColorLeft(BaseColor.BLUE);
table.getDefaultCell().setBorderColorRight(BaseColor.BLUE);
table.getDefaultCell().setBorderWidthTop(1f);
table.getDefaultCell().setBorderWidthLeft(1f);
table.getDefaultCell().setBorderWidthRight(1f);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
Font font1 = new Font(FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE);
table.addCell(new Phrase("CONTROLLED COPY", font1));
table.getDefaultCell().setFixedHeight(20);
table.getDefaultCell().setBorder(Rectangle.LEFT);
table.getDefaultCell().setBorder(Rectangle.RIGHT);
table.getDefaultCell().setBorderColorLeft(BaseColor.BLUE);
table.getDefaultCell().setBorderColorRight(BaseColor.BLUE);
table.getDefaultCell().setBorderWidthLeft(1f);
table.getDefaultCell().setBorderWidthRight(1f);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
Font font = new Font(FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.RED);
table.addCell(new Phrase(month, font));
table.getDefaultCell().setFixedHeight(20);
table.getDefaultCell().setBorder(Rectangle.LEFT);
table.getDefaultCell().setBorder(Rectangle.RIGHT);
table.getDefaultCell().setBorder(Rectangle.BOTTOM);
table.getDefaultCell().setBorderColorLeft(BaseColor.BLUE);
table.getDefaultCell().setBorderColorRight(BaseColor.BLUE);
table.getDefaultCell().setBorderColorBottom(BaseColor.BLUE);
table.getDefaultCell().setBorderWidthLeft(1f);
table.getDefaultCell().setBorderWidthRight(1f);
table.getDefaultCell().setBorderWidthBottom(1f);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(new Phrase("BLR DESIGN DEPT.", font1));
return table;
}
is there any method by which I can read each page and if there is no text in that part add the stamp else search for nearest available free space, just like what a density scanner does?
iText does not offer that functionality out of the box. Depending of what kind of content you want to evade, though, you might consider either rendering the page to an image and looking for white spots in the image or doing text extraction with a strategy that tries to find locations without text.
The first alternative, analyzing a rendered version of the page, would be the focus of a separate question as an image processing library would have to be chosen first.
There are a number of situations, though, in which that first alternative is not the best way to go. E.g. if you only want to evade text but not necessarily graphics (like watermarks), or if you also want to evade invisible text (which usually can be marked in a PDF viewer and, therefore, interfere with your addition).
The second alternative (using text and image extraction abilities of iText) can be the more appropriate approach in such situations.
Here a sample RenderListener for such a task:
public class FreeSpaceFinder implements RenderListener
{
//
// constructors
//
public FreeSpaceFinder(Rectangle2D initialBox, float minWidth, float minHeight)
{
this(Collections.singleton(initialBox), minWidth, minHeight);
}
public FreeSpaceFinder(Collection<Rectangle2D> initialBoxes, float minWidth, float minHeight)
{
this.minWidth = minWidth;
this.minHeight = minHeight;
freeSpaces = initialBoxes;
}
//
// RenderListener implementation
//
#Override
public void renderText(TextRenderInfo renderInfo)
{
Rectangle2D usedSpace = renderInfo.getAscentLine().getBoundingRectange();
usedSpace.add(renderInfo.getDescentLine().getBoundingRectange());
remove(usedSpace);
}
#Override
public void renderImage(ImageRenderInfo renderInfo)
{
Matrix imageMatrix = renderInfo.getImageCTM();
Vector image00 = rect00.cross(imageMatrix);
Vector image01 = rect01.cross(imageMatrix);
Vector image10 = rect10.cross(imageMatrix);
Vector image11 = rect11.cross(imageMatrix);
Rectangle2D usedSpace = new Rectangle2D.Float(image00.get(Vector.I1), image00.get(Vector.I2), 0, 0);
usedSpace.add(image01.get(Vector.I1), image01.get(Vector.I2));
usedSpace.add(image10.get(Vector.I1), image10.get(Vector.I2));
usedSpace.add(image11.get(Vector.I1), image11.get(Vector.I2));
remove(usedSpace);
}
#Override
public void beginTextBlock() { }
#Override
public void endTextBlock() { }
//
// helpers
//
void remove(Rectangle2D usedSpace)
{
final double minX = usedSpace.getMinX();
final double maxX = usedSpace.getMaxX();
final double minY = usedSpace.getMinY();
final double maxY = usedSpace.getMaxY();
final Collection<Rectangle2D> newFreeSpaces = new ArrayList<Rectangle2D>();
for (Rectangle2D freeSpace: freeSpaces)
{
final Collection<Rectangle2D> newFragments = new ArrayList<Rectangle2D>();
if (freeSpace.intersectsLine(minX, minY, maxX, minY))
newFragments.add(new Rectangle2D.Double(freeSpace.getMinX(), freeSpace.getMinY(), freeSpace.getWidth(), minY-freeSpace.getMinY()));
if (freeSpace.intersectsLine(minX, maxY, maxX, maxY))
newFragments.add(new Rectangle2D.Double(freeSpace.getMinX(), maxY, freeSpace.getWidth(), freeSpace.getMaxY() - maxY));
if (freeSpace.intersectsLine(minX, minY, minX, maxY))
newFragments.add(new Rectangle2D.Double(freeSpace.getMinX(), freeSpace.getMinY(), minX - freeSpace.getMinX(), freeSpace.getHeight()));
if (freeSpace.intersectsLine(maxX, minY, maxX, maxY))
newFragments.add(new Rectangle2D.Double(maxX, freeSpace.getMinY(), freeSpace.getMaxX() - maxX, freeSpace.getHeight()));
if (newFragments.isEmpty())
{
add(newFreeSpaces, freeSpace);
}
else
{
for (Rectangle2D fragment: newFragments)
{
if (fragment.getHeight() >= minHeight && fragment.getWidth() >= minWidth)
{
add(newFreeSpaces, fragment);
}
}
}
}
freeSpaces = newFreeSpaces;
}
void add(Collection<Rectangle2D> rectangles, Rectangle2D addition)
{
final Collection<Rectangle2D> toRemove = new ArrayList<Rectangle2D>();
boolean isContained = false;
for (Rectangle2D rectangle: rectangles)
{
if (rectangle.contains(addition))
{
isContained = true;
break;
}
if (addition.contains(rectangle))
toRemove.add(rectangle);
}
rectangles.removeAll(toRemove);
if (!isContained)
rectangles.add(addition);
}
//
// members
//
public Collection<Rectangle2D> freeSpaces = null;
final float minWidth;
final float minHeight;
final static Vector rect00 = new Vector(0, 0, 1);
final static Vector rect01 = new Vector(0, 1, 1);
final static Vector rect10 = new Vector(1, 0, 1);
final static Vector rect11 = new Vector(1, 1, 1);
}
Using this FreeSpaceFinder you can find empty areas with given minimum dimensions in a method like this:
public Collection<Rectangle2D> find(PdfReader reader, float minWidth, float minHeight, int page) throws IOException
{
Rectangle cropBox = reader.getCropBox(page);
Rectangle2D crop = new Rectangle2D.Float(cropBox.getLeft(), cropBox.getBottom(), cropBox.getWidth(), cropBox.getHeight());
FreeSpaceFinder finder = new FreeSpaceFinder(crop, minWidth, minHeight);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
parser.processContent(page, finder);
return finder.freeSpaces;
}
For your task you now have to choose from the returned rectangles the one which suits you best.
Beware, this code still may have to be tuned to your requirements:
It ignores clip paths, rendering modes, colors, and covering objects. Thus, it considers all text and all bitmap images, whether they are actually visible or not.
It does not consider vector graphics (because the iText parser package does not consider them).
It is not very optimized.
Applied to this PDF page:
with minimum width 200 and height 50, you get these rectangles:
x y w h
000,000 000,000 595,000 056,423
000,000 074,423 595,000 168,681
000,000 267,304 314,508 088,751
000,000 503,933 351,932 068,665
164,296 583,598 430,704 082,800
220,803 583,598 374,197 096,474
220,803 583,598 234,197 107,825
000,000 700,423 455,000 102,396
000,000 700,423 267,632 141,577
361,348 782,372 233,652 059,628
or, more visually, here as rectangles on the page:
The paper plane is a vector graphic and, therefore, ignored.
Of course you could also change the PDF rendering code to not draw stuff you want to ignore and to visibly draw originally invisible stuff which you want to ignore, and then use bitmap image analysis nonetheless...
EDIT
In his comments the OP asked how to find the rectangle in the rectangle collection returned by find which is nearest to a given point.
First of all there not necessarily is the nearest rectangle, there may be multiple.
That been said, one can choose a nearest rectangle as follows:
First one needs to calculate a distance between point and rectangle, e.g.:
double distance(Rectangle2D rectangle, Point2D point)
{
double x = point.getX();
double y = point.getY();
double left = rectangle.getMinX();
double right = rectangle.getMaxX();
double top = rectangle.getMaxY();
double bottom = rectangle.getMinY();
if (x < left) // point left of rect
{
if (y < bottom) // and below
return Point2D.distance(x, y, left, bottom);
if (y > top) // and top
return Point2D.distance(x, y, left, top);
return left - x;
}
if (x > right) // point right of rect
{
if (y < bottom) // and below
return Point2D.distance(x, y, right, bottom);
if (y > top) // and top
return Point2D.distance(x, y, right, top);
return x - right;
}
if (y < bottom) // and below
return bottom - y;
if (y > top) // and top
return y - top;
return 0;
}
Using this distance measurement one can select a nearest rectangle using code like this for a Collection<Rectangle2D> rectangles and a Point2D point:
Rectangle2D best = null;
double bestDist = Double.MAX_VALUE;
for (Rectangle2D rectangle: rectangles)
{
double distance = distance(rectangle, point);
if (distance < bestDist)
{
best = rectangle;
bestDist = distance;
}
}
After this best contains a best rectangle.
For the sample document used above, this method returns the colored rectangles for the page corners and left and right centers:
EDIT TWO
Since iText 5.5.6, the RenderListener interface has been extended as ExtRenderListener to also be signaled about Path construction and path drawing operations. Thus, the FreeSpaceFinder above could also be extended to handle paths:
//
// Additional ExtRenderListener methods
//
#Override
public void modifyPath(PathConstructionRenderInfo renderInfo)
{
List<Vector> points = new ArrayList<Vector>();
if (renderInfo.getOperation() == PathConstructionRenderInfo.RECT)
{
float x = renderInfo.getSegmentData().get(0);
float y = renderInfo.getSegmentData().get(1);
float w = renderInfo.getSegmentData().get(2);
float h = renderInfo.getSegmentData().get(3);
points.add(new Vector(x, y, 1));
points.add(new Vector(x+w, y, 1));
points.add(new Vector(x, y+h, 1));
points.add(new Vector(x+w, y+h, 1));
}
else if (renderInfo.getSegmentData() != null)
{
for (int i = 0; i < renderInfo.getSegmentData().size()-1; i+=2)
{
points.add(new Vector(renderInfo.getSegmentData().get(i), renderInfo.getSegmentData().get(i+1), 1));
}
}
for (Vector point: points)
{
point = point.cross(renderInfo.getCtm());
Rectangle2D.Float pointRectangle = new Rectangle2D.Float(point.get(Vector.I1), point.get(Vector.I2), 0, 0);
if (currentPathRectangle == null)
currentPathRectangle = pointRectangle;
else
currentPathRectangle.add(pointRectangle);
}
}
#Override
public Path renderPath(PathPaintingRenderInfo renderInfo)
{
if (renderInfo.getOperation() != PathPaintingRenderInfo.NO_OP)
remove(currentPathRectangle);
currentPathRectangle = null;
return null;
}
#Override
public void clipPath(int rule)
{
// TODO Auto-generated method stub
}
Rectangle2D.Float currentPathRectangle = null;
(FreeSpaceFinderExt.java)
Using this class the result above is improved to
As you see the paper plane and the table background colorations now also are taken into account.
My other answer focuses on the original question, i.e. how to find free space with given minimum dimensions on a page.
Since that answer had been written, the OP provided code trying to make use of that original answer.
This answer deals with that code.
The code has a number of shortcoming.
The choice of free space on a page depends on the number of pages in the document.
The reason for this is to be found at the start of the loop over the pages:
for(int i = 1; i <= n; i++)
{
Collection<Rectangle2D> rectangles = find(reader, 300, 100, n, stamper);
...
The OP surely meant i, not n there. The code as is always looks for free space on the last document page.
The rectangles are lower than they should be.
The reason for this is to be found in the retrieval and use of the rectangle coordinates:
x = (float) best.getX();
y = (float) best.getY();
...
getFooterTable(i, n).writeSelectedRows(0, -1, x, y, stamper.getOverContent(i));
The Rectangle2D methods getX and getY return the coordinates of the lower left rectangle corner; the PdfPTable methods writeSelectedRows, on the other hand, require the upper left rectangle corner. Thus, getMaxY should be used instead of getY.

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));

How do I create a bar chart using the Java prefuse library?

I've currently got prefuse to plot a scatter graph, where the X axis is the computer name and the Y axis is its temperature. How do I get it to draw bars showing the values instead of discrete points?
I'm currently using the following code to render the points:
ShapeAction shape = new ShapeAction(group, Constants.SHAPE_RECTANGLE);
ColorAction strokeColor = new DataColorAction(group, dataType, Constants.NUMERICAL, VisualItem.STROKECOLOR, colorPalette);
ActionList draw = new ActionList();
draw.add(shape);
draw.add(strokeColor);
draw.add(new ColorAction(group, VisualItem.FILLCOLOR, 0));
draw.add(new RepaintAction());
m_vis.putAction("draw", draw);
How would I adapt this code to get, instead of a small square at each point, a thick bar going from th bottom of the graph to the point?
Thanks.
I think I should probably point out how I did this - Stack Overflow is supposed to be a repository too, after all. Earlier in the code was the following:
m_vis.setRendererFactory(new RendererFactory() {
Renderer yAxisRenderer = new AxisRenderer(Constants.LEFT, Constants.TOP);
Renderer xAxisRenderer = new AxisRenderer(Constants.CENTER, Constants.FAR_BOTTOM);
Renderer barRenderer = new ShapeRenderer();
public Renderer getRenderer(VisualItem item) {
return item.isInGroup("yAxis") ? yAxisRenderer :
item.isInGroup("xAxis") ? xAxisRenderer :
barRenderer;
}
});
I extended the shape renderer to always return a rectangle of the correct width and height, and positioned it half a bar to the left of where it was supposed to be. If you want to position your bars in the centre, you need to do that yourself - prefuse won't help you.
m_vis.setRendererFactory(new RendererFactory() {
Renderer yAxisRenderer = new AxisRenderer(Constants.LEFT, Constants.TOP);
Renderer xAxisRenderer = new AxisRenderer(Constants.CENTER, Constants.FAR_BOTTOM);
Renderer barRenderer = new ShapeRenderer() {
protected Shape getRawShape(VisualItem item) {
double x = item.getX();
double y = item.getY();
if (Double.isNaN(x) || Double.isInfinite(x))
x = getInsets().left + axisWidth + totalBarWidth / 2;
if (Double.isNaN(y) || Double.isInfinite(y))
y = 0;
double width = totalBarWidth / (barCount + 1) - barGap;
double height = getHeight() - getInsets().bottom - axisHeight - y;
x -= width / 2;
return rectangle(x, y, width, height);
}
};
public Renderer getRenderer(VisualItem item) {
return item.isInGroup("yAxis") ? yAxisRenderer :
item.isInGroup("xAxis") ? xAxisRenderer :
barRenderer;
}
});

Categories