I want to draw coefficient histogram of JPEG. I'm searching on Google for hours to know how to use Chart2D library, but there is no tutorial with examples. The array which I want to draw is hist[]. I created an object of LBChart2D, but I don't know how to set the array as data set to it.
//coeff[] is the coefficients array
for(int i=0;i<coeff.length;i++)
hist[coeff[i]]++;
LBChart2D lbChart2D = new LBChart2D();
EDIT:Here is what I'm trying :
Object2DProperties object2DProps = new Object2DProperties();
object2DProps.setObjectTitleText ("Title ");
Chart2DProperties chart2DProps = new Chart2DProperties();
chart2DProps.setChartBetweenChartAndLegendGapThicknessModel(5);
LegendProperties legendProps = new LegendProperties();
legendProps .setLegendBorderThicknessModel(5);
legendProps.setLegendBackgroundColor(Color.yellow);
legendProps.setLegendExistence (false);
GraphChart2DProperties graph2DProps = new GraphChart2DProperties();
GraphProperties graphProps = new GraphProperties();
object2DProps .setObjectTitleFontName("test");
Dataset dataset = new Dataset (1, hist.length, 1);
for(int i=0;i<hist.length;i++)
dataset.set (0, i, 0, hist[i]) ;
LBChart2D lbChart2D = new LBChart2D();
lbChart2D.setObject2DProperties (object2DProps);
lbChart2D.setChart2DProperties (chart2DProps);
lbChart2D.setLegendProperties (legendProps);
lbChart2D.setGraphChart2DProperties (graph2DProps);
lbChart2D.addGraphProperties (graphProps);
lbChart2D.addDataset (dataset);
lbChart2D.setSize(width, height);
BufferedImage lbImage = lbChart2D.getImage();
jLabel15.setIcon(new ImageIcon(lbImage));
Now It produces an Exception java.lang.NullPointerException on this line:
BufferedImage lbImage = lbChart2D.getImage();
What's wrong?
Several Chart2D demos are included in the distribution. You can collect the data from a BufferedImage obtained via ImageIO. See also jfreechart.
Addendum: Absent a complete example, you can use validate() to get debug messages. At a minimum, verify that you invoke setLabelsAxisLabelsTexts() with hist.length labels.
//Optional validation: Prints debug messages if invalid only.
if (!chart2D.validate(false)) {
chart2D.validate(true);
}
Thanks #trashgod for trying to help me. Don't worry I've got it.
I used jfreechart library to draw the histogram, and here is the code I used.
int hist[]=new int[11];
int val[]=new int[11];
for(int ii=0;ii<11;ii++)
hist[ii]=ii-5;//to get negative indeces I used an array to save them
for(int kk=0;kk<coeff.length;kk++)
if(coeff[kk]<=5 &coeff[kk]>=-5) val[coeff[kk]+5]++;
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for(int ii=0;ii<hist.length;ii++)
dataset.setValue(val[ii], "Coefficient value",""+hist[ii]);
JFreeChart chart = ChartFactory.createBarChart("Original Histogram",
"Coefficient value", "", dataset,
PlotOrientation.VERTICAL, false,true, false);
//chart.setBackgroundPaint(Color.yellow);
chart.getTitle().setPaint(Color.blue);
CategoryPlot p = chart.getCategoryPlot();
p.setOutlinePaint(Color.BLUE);
p.setRangeGridlinePaint(Color.blue);
orgim=chart.createBufferedImage(400,400);
Image im1= orgim.getScaledInstance(jLabel12.getWidth(),jLabel12.getHeight(),1);
jLabel12.setIcon(new ImageIcon(im1));
///
Related
I am currently comparing time-series. They are stored in InfluxDB. My task is to get two time-series from InfluxDB, compare them and upload a visualization to Grafana. The comparison result would be output to console and the two time-series would be uploaded to Grafana in a dashboard and they should be in the same panel. I am trying to use the grafana-api-java-client found here. My problem is that I can not figure out how to do this with the provided examples and Javadocs. There is not a lot of documentation and the examples don't work properly in my case. I hope that someone has worked with this client and can explain how to properly add two time-series to a panel in a dashboard and upload it.
I will provide what I am doing and then post the examples from the github page of the API.
First of all this is how I am getting my time series:
public List<Double> getTimeSeries(String streetName, String start, String stop) {
//gets the query result
QueryResult queryResult = influxDB.query(new Query(String.format("SELECT value FROM your_measurement WHERE street='%s' " +
"AND time >= '%s' AND time <= '%s'", streetName, start, stop)));
//Gets the values from the query result
List<List<Object>> values = queryResult.getResults().iterator().next().getSeries().iterator().next().getValues();
//Adds the values to a list
List<Double> timeSeries = new ArrayList<>();
for (List<Object> li : values) {
timeSeries.add(Double.valueOf(li.get(1).toString()));
}
return timeSeries;
}
I can convert this list to an array of doubles:
double[] timeSeriesArray = timeSeries.stream().mapToDouble(d -> d).toArray();
The following is the first example. It works properly up until the getDashboard() and deleteDashboard() methods, where I get the error that such a dashboard does not exist, even though it does. I don't know what causes this error. Every new dashboard ends up in the folder "General". The method createDashboard() creates, as expected, an empty dashboard in Grafana.
import com.appnexus.grafana.client.GrafanaClient;
//Setup the client
GrafanaConfiguration grafanaConfiguration =
new GrafanaConfiguration().host("your_grafana_host").apiKey("Bearer your_secret_key");
GrafanaClient grafanaClient = new GrafanaClient(grafanaConfiguration);
//Setup the dashboard
String DASHBOARD_NAME = "new_dashboard";
Dashboard dashboard = new Dashboard()
.title(DASHBOARD_NAME)
.version(0);
GrafanaDashboard grafanaDashboard = new GrafanaDashboard().dashboard(dashboard);
//Make API calls
grafanaClient.createDashboard(grafanaDashboard);
grafanaClient.getDashboard(DASHBOARD_NAME);
grafanaClient.deleteDashboard(DASHBOARD_NAME);
This is the second example. I assume that I have to modify it in order to solve my problem. I had to replace two things to get this example to work, which I will explain with code comments. When executing this code it creates a dashboard with an empty panel. I expected something to be shown on the panel but it is empty and there are no axes.
import com.appnexus.grafana.client.GrafanaClient;
//Setup the client
GrafanaConfiguration grafanaConfiguration =
new GrafanaConfiguration().host("your_grafana_host").apiKey("Bearer your_secret_key");
GrafanaClient grafanaClient = new GrafanaClient(grafanaConfiguration);
//Setup the dashboard
String DASHBOARD_NAME = "new_dashboard";
DashboardPanelTarget dashboardPanelTarget =
new DashboardPanelTarget().refId("getSomeMetric").target("*");
DashboardPanelXAxis dashboardPanelXAxis =
new DashboardPanelXAxis().show(true).mode(DashboardPanelXAxis.Mode.TIME);
DashboardPanelYAxis dashboardPanelYAxis =
new DashboardPanelYAxis().format(DashboardPanelYAxis.Format.SHORT).logBase(1).show(true);
//Datasource is required or alerts cannot be added
DashboardPanel dashboardPanel =
new DashboardPanel()
//This might be where my data has to go but I am not sure.
.targets(new ArrayList<>(Collections.singletonList(dashboardPanelTarget)))
//Had to change DASHBOARD_DATA_SOURCE to a String -> "DASHBOARD_DATA_SOURCE", I assume it's just the name of the datasource.
//.datasource(DASHBOARD_DATA_SOURCE)
.datasource("DASHBOARD_DATA_SOURCE")
.type(DashboardPanel.Type.GRAPH)
.fill(1)
.title(dashboardName)
.linewidth(1)
.lines(true)
.height("300px")
.span(12)
.xaxis(dashboardPanelXAxis)
.yaxes(new ArrayList<>(Arrays.asList(dashboardPanelYAxis, dashboardPanelYAxis)));
DashboardRow dashboardRow =
new DashboardRow()
.collapse(false)
.panels(new ArrayList<>(Collections.singletonList(dashboardPanel)));
Dashboard dashboard =
new Dashboard()
.title(dashboardName)
.schemaVersion(1)
.rows(new ArrayList<>(Collections.singletonList(dashboardRow)));
DashboardMeta dashboardMeta = new DashboardMeta().canSave(true).slug(dashboardName);
GrafanaDashboard grafanaDashboard =
new GrafanaDashboard().meta(dashboardMeta).dashboard(dashboard);
//create new dashboard
//Had to change createDashboardTest() to createDashboard(), because createDashboardTest() doesn't seem to exist
//DashboardMeta createdDashboardMeta = createDashboardTest(grafanaDashboard);
DashboardMeta createdDashboardMeta = createDashboard(grafanaDashboard);
I want to share diamond detail in table format(Plain text not HTML)
I have made this using this library but its prints the data properly using the system.out but while I sharing it, its format is changed:
Below is my code:
List<String> headersList = Arrays.asList("", "");
List<List<String>> rowsList = Arrays.asList(
Arrays.asList("Stone Id :", details[0]),
Arrays.asList("Lab", details[1]),
Arrays.asList("Shape", details[2]),
Arrays.asList("Carat", details[3]),
Arrays.asList("Clarity-Color", details[4]),
Arrays.asList("Cut-Pol-Sym-Flou", details[5]));
Board board = new Board(75);
Table table = new Table(board, 75, headersList, rowsList);
table.invalidate().setGridMode(Table.GRID_NON).setRowsList(rowsList);
List<Integer> colWidthsList = Arrays.asList(30, 14);
table.setColWidthsList(colWidthsList);
Block tableBlock = table.tableToBlocks();
board.setInitialBlock(tableBlock);
board.build();
String preview1 = board.getPreview();
System.out.print(preview1);
sharingIntent.putExtra(Intent.EXTRA_TEXT,preview1);
The console uses monospaced font which takes exactly same width for all characters. But your view isn't using it, so it looks messed up.
Use a monospaced font.
Or use a tabular format. Perhaps a ListView with each row having two text views side by side having fixed width.
I have a table that contains some data. I know that I can access of my first row like this,
Object nameOfFile = Main_Menu.jTable3.getValueAt(0, 0);
String nameOfFileToString = nameOfFile.toString();
My table is dynamic. Sometimes my row of the table is 100, sometimes is 200. How can I get the last row of my table even my table is dynamically change.
P.S : my table is connected with a jfreechart, so I need this for my update Y axis in jfreechart like this
Object nameOfFile = Main_Menu.jTable3.getValueAt(0, 0);
String nameOfFileToString = nameOfFile.toString();
// create the chart...
final JFreeChart chart = ChartFactory.createLineChart(
"Persentastion Of Similarity", // chart title
"", // domain axis label
nameOfFileToString, // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
true, // include legend
true, // tooltips
false // urls
);
for the help, thanks
You can use JTable.getModel().getRowCount() to get the number of rows; the rest is straightforward:
Object nameOfFile = Main_Menu.jTable3.getValueAt(jTable3.getModel().getRowCount()-1, 0);
// go on with your code
Thank you so much for all of you.
This code is rock
Object nameOfFile = Main_Menu.jTable3.getValueAt(jTable3.getModel().getRowCount()-1, 0);
Now, my application is looking fine. I haven't try getrowSorter but soon I will try.
Once again, thanks...
How can I do in order to show less values on the X axis, to get the data organized?
However I want the values are all shown. One idea I had was to use the zoom so you can see all the records, but do not know if it was a good idea, or rather do not even know it.
As you can see in the picture my idea is that data more legible, in order to realize the best of everything.
Does anyone can help me please?
//Code with result from query and chart create
String query="select (CONCAT(`date`, ' ', hour)), temperature from records where idTermomether like 'T1' and date between '2014-06-01' and '2014-06-03'";
JDBCCategoryDataset dataset = new JDBCCategoryDataset (CriaConexao.getConexao(),query);
JFreeChart chart = ChartFactory.createLineChart(" - Temperature", "Date", "Temperature", dataset, PlotOrientation.VERTICAL, false, true, true);
BarRenderer renderer = null;
CategoryPlot plot= chart.getCategoryPlot();
CategoryAxis xAxis=(CategoryAxis)plot.getDomainAxis();
xAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_90);
renderer=new BarRenderer();
ChartFrame frame = new ChartFrame("Temperature", chart);
frame.setVisible(true);
frame.setSize(400,650);
Is there a way of creating and inserting a bar chart in a Ms Word document using Aspose Words for Java? I can't find a way to do this. Thanks.
Aspose.Words for Java currently doesn't allow you to create the bar chart in Word documents. However, if you just want to add a static bar chart, you may try Aspose.Cells for Java to create bar chart and render it to image. After that, you can add this bar chart image in Word document using Aspose.Words for Java. Do you think this might help in your scenario? If it does then you can use the following code snippet to create and render the bar chart to image:
//Create a new Workbook.
Workbook workbook = new Workbook();
//Get the first worksheet.
Worksheet sheet = workbook.getWorksheets().get(0);
//Set the name of worksheet
sheet.setName("Data");
//Get the cells collection in the sheet.
Cells cells = workbook.getWorksheets().get(0).getCells();
//Put some values into a cells of the Data sheet.
cells.get("A1").setValue("Region");
cells.get("A2").setValue("France");
cells.get("A3").setValue("Germany");
cells.get("A4").setValue("England");
cells.get("A5").setValue("Sweden");
cells.get("A6").setValue("Italy");
cells.get("A7").setValue("Spain");
cells.get("A8").setValue("Portugal");
cells.get("B1").setValue("Sale");
cells.get("B2").setValue(70000);
cells.get("B3").setValue(55000);
cells.get("B4").setValue(30000);
cells.get("B5").setValue(40000);
cells.get("B6").setValue(35000);
cells.get("B7").setValue(32000);
cells.get("B8").setValue(10000);
//Create chart
int chartIndex = sheet.getCharts().add(ChartType.COLUMN, 12, 1, 33,
12);
Chart chart = sheet.getCharts().get(chartIndex);
//Set properties of chart title
chart.getTitle().setText("Sales By Region");
chart.getTitle().getTextFont().setBold(true);
chart.getTitle().getTextFont().setSize(12);
//Set properties of nseries
chart.getNSeries().add("Data!B2:B8", true);
chart.getNSeries().setCategoryData("Data!A2:A8");
//Set the fill colors for the series's data points (France -
Portugal(7 points))
ChartPointCollection chartPoints =
chart.getNSeries().get(0).getPoints();
ChartPoint point = chartPoints.get(0);
point.getArea().setForegroundColor(Color.getCyan());
point = chartPoints.get(1);
point.getArea().setForegroundColor(Color.getBlue());
point = chartPoints.get(2);
point.getArea().setForegroundColor(Color.getYellow());
point = chartPoints.get(3);
point.getArea().setForegroundColor(Color.getRed());
point = chartPoints.get(4);
point.getArea().setForegroundColor(Color.getBlack());
point = chartPoints.get(5);
point.getArea().setForegroundColor(Color.getGreen());
point = chartPoints.get(6);
point.getArea().setForegroundColor(Color.getMaroon());
//Set the legend invisible
chart.setShowLegend(false);
//Get the Chart mage
ImageOrPrintOptions imgOpts = new ImageOrPrintOptions();
imgOpts.setImageFormat(ImageFormat.getPng());
//Save the chart image file.
chart.toImage(new FileOutputStream("D:\Files\MyChartImage.png"),
imgOpts);
Disclosure: I work as developer evangelist at Aspose.