I am looking for options to export a jfreechart (available in a JSP+struts) to an excel sheet.
I have tried 'setting the response header to type msexcel' to export the entire JSP to excel, but it is not rendering the jfreechart image.
Is there anyother option to export the jfreechart to excel?
I have generated the chart using jfreechart and used POI for exporting it to excel.
ServletOutputStream stream=resp.getOutputStream();
resp.setContentType("application/vnd.ms-excel");
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
int imageWidth= 700;
int imageHeigth = 400;
JFreeChart chart=ChartFactory.createBarChart("Test Chart", "", "", dataset, PlotOrientation.VERTICAL, true, true, false);
ChartUtilities.writeChartAsJPEG(outStream, chart, imageWidth, imageHeigth);
byte[] imageInByte = outStream.toByteArray();
outStream.close();
int pictureIdx =wb.addPicture(imageInByte,Workbook.PICTURE_TYPE_JPEG);
Drawing drawing = sheet.createDrawingPatriarch();
CreationHelper helper = wb.getCreationHelper();
//add a picture shape
ClientAnchor anchor = helper.createClientAnchor();
//set top-left corner of the picture,
//subsequent call of Picture#resize() will operate relative to it
anchor.setCol1(3);
anchor.setRow1(4);
Picture pict = drawing.createPicture(anchor, pictureIdx);
//auto-size picture relative to its top-left corner
pict.resize();
wb.write(outStream);
stream.write(outStream.toByteArray());
Apache POI will not help you because it has a limitiation (read the manual at Apache website). It can plot line and scattered charts only, that's look very poor.
Library good for working with excel but not for building a graphs. My suggestion is use prepared in advance templates, adjust it and just transfer necessary data from Java to template.
Another way it is use rendered JPEG, but it is horrible things and do not do this.
Related
I used the (new) GUI Builder and inserted an image (by way of adding a Label). However, it appears too big. Is there anyway I can scale and control the size? (I saw something which points to cloudinary but that seems too complicated. I just want to simply scale down the image.)
There are several ways to resize images in Codename One and I will mention few below:
1.
Use MultiImages in the GUI Builder. With this multiple sizes of images are generated from one image based on the sizes you specified. In your GUI Builder, Click Images -> Add Multi Images -> Select your image -> Check Preserve Aspect Ratio -> Increase the % that represents the percentage of the screen width you want the image to occupy. Set any DPI you don't require to 0.
2.
Use ScaledImageLabel or ScaledImageButton, it will resize the image the fill available space the component is occupying.
3.
Scale the image itself in code (This is not efficient, though):
public static Image getImageFromTheme(String name) {
try {
Resources resFile = Resources.openLayered("/theme");
Image image = resFile.getImage(name);
return image;
} catch (IOException ioe) {
//Log.p("Image " + name + " not found: " + ioe);
}
return null;
}
Image resizedImage = getImageFromTheme("myImage").scaledWidth(Math.round(Display.getInstance().getDisplayWidth() / 10)); //change value as necessary
4.
Mutate the image (Create an image from another image).
How I can create interactive R plots in Power BI (for example Plotly)? Below code doesn't return any error, but also doesn't show chart:
library(plotly)
library(ggplot2)
z = ggplot(data = dataset) + geom_point(mapping = aes(x = Console, y = Search))
ggplotly(z)
Data source:
source <- "https://cdn.rawgit.com/BlueGranite/Microsoft-R-Resources/master/power-bi/gameconsole.csv"
game.console <- read.csv(source, header = TRUE)
According to this question in Power BI's Community forums
Plotly lib is supported as part of HTML support for R powered Custom
Visuals only, not R Visuals in general currently.
Plotly can only be used if it produces an IMAGE\PNG for R visuals in
PBI. Not HTML.
For Custom Visuals we have an upcoming feature which will also enable R-based custom visuals to render as htmls.
Hope this helps.
The reason is that right now Power BI only supports render charts created by R visualization component as PNG.
Try the following:
p <- plot_ly(x = dataset$period, y = dataset$mean, name = "spline", line = list(shape = "spline"))
plotly_IMAGE(p, format = "png", out_file = "out.png")
But the problem with this is that, though rendered by plotly, the visualizations will not be interactive since its just a PNG image.
If you want to create interactive visualizations using plotly. The only way you can do is to create a custom Power BI visualization and import it to your report. See this post for a good introduction.
PowerBI only supports charts rendered as PNG while plotly format is in HTML. You can try to save the chart as PNG then print it in the R console inside PowerBI.
You first have to register a plotly account here.
After registration, on the top right corner arrow next to your account name and click on Settings -> API keys. You will be able to generate API key. Copy and paste your username and API key using this code.
Sys.setenv("plotly_username"="....")
Sys.setenv("plotly_api_key"=".....")
Then add this code in to turn the plot into png format and print it out.
fig <- plot_ly(x = dataset$Console, y = dataset$Search)
Png <- plotly_IMAGE(fig, out_file = "plotly-test-image.png")
print(Png)
As mentioned in another answer, this plot won't be interactive as plot in PowerBI. To create an interactive plot in PowerBI, you have to create a custom visual. Follow an R custom visual example here or radacad example here.
I'm developing an app that displays daily financial data, and have chosen to use JFreeChart. I was able to learn how to create a candlestick chart, but my problem lies in customization.
You see, what I'm aiming for is more along the lines of
While, so far all I've been able to manage is
.
No matter how far I zoom in, the candlesticks do not increase in width.
I'm fairly certain that somehow the thin candlesticks have something to do with being bound to a certain time range.. I've tried to remedy that but am not sure what I'm doing wrong here.
SSCE
public void showStockHistory(OHLCDataset dataset, String stockName) {
JFreeChart candleChart = ChartFactory.createCandlestickChart("History of " + stockName, "Date", "Stock Points", dataset, true);
XYPlot plot = candleChart.getXYPlot();
plot.setDomainPannable(true);
plot.setRangePannable(true);
ValueAxis domain = plot.getDomainAxis();
domain.setAutoRange(true);
NumberAxis range = (NumberAxis)plot.getRangeAxis();
range.setUpperMargin(0.0D);
range.setLowerMargin(0.0D);
range.setAutoRange(true);
range.setAutoRangeIncludesZero(false);
ChartPanel chartPanel = new ChartPanel(candleChart);
chartPanel.setMouseWheelEnabled(true);
chartPanel.setMouseZoomable(true);
getViewport().add(chartPanel);
}
Although my given example seems to have to no differing method calls from the demo in the first picture's code above, it nevertheless only shows thin candlesticks. I assume this to be some kind of bug.
However, I was able to rectify the issue as follows:
getting the renderer for the chart,
casting it to a type of CandlestickRenderer, and
setting its setAutoWidthMethod() method to CandlestickRenderer.WIDTHMETHOD_SMALLEST.
This is how you do it:
JFreeChart candleChart = ChartFactory.createCandlestickChart(
"History of " + stockName, "Date", "Stock Points", dataset, true);
XYPlot plot = candleChart.getXYPlot();
CandlestickRenderer renderer = (CandlestickRenderer) plot.getRenderer();
renderer.setAutoWidthMethod(CandlestickRenderer.WIDTHMETHOD_SMALLEST);
I am trying to create a simple 3d pie chart using jfreechart in NetBeans IDE.My code is given below :-
DefaultPieDataset pieDataset = new DefaultPieDataset();
pieDataset.setValue("One", new Integer(10));
pieDataset.setValue("Two", new Integer(20));
pieDataset.setValue("Three", new Integer(30));
pieDataset.setValue("Four", new Integer(40));
JFreeChart chart = ChartFactory.createPieChart("Pie Chart", pieDataset,true,true,false);
PiePlot3D plot = (PiePlot3D) chart.getPlot (); // <--error in this line
However, the last line shows the error "Incompatible types : Plot cannot be converted to piePlot3D" . Many examples i found on the internet uses the same line of code without any error. I have included all the necessary imports but still the error is shown. How can I fix this error?
You need to use the createPieChart3D() method in the ChartFactory class (you missed the '3D' on the end of the method name).
You should also look at the 3D pie charts in Orson Charts - these use real 3D projections, so they are a bit nicer. I am the author of both libraries.
Do my tiles need to adhere to any particular specs?
I have a large image file which I'd like to turn into a map with LeafletJS. I am going to be using the Python Imaging Library to cut it up into all the various tiles I need.
However, I can't find any information about using custom maps in Leaflet. Do I provide Leaflet with the range of X,Y,Z info somehow? Do I give it the pixel size of each tile? Does it figure this out on its own?
To put my question into one concise question: What do I need to do in order to have image files that can double as map tiles with LeafletJS, and what, if anything, do I need to do in my front-end script? (beyond the obvious specifying of my custom URL)
You are looking for a TileLayer. In this TileLayer, you give the URL for the to-be-fetched images to leaflet with a template like this:
http://{s}.somedomain.com/blabla/{z}/{x}/{y}.png
When you are at the specified zoom, x and y level, Leaflet will automatically fetch the tiles on the URL you gave.
Depending on the image you want to show, the bigger part of the work will however be in the tile generation. Tiles by default have a 256x256px size (can be changed in the TileLayer options), and if you are using geodata the used projection is Mercator projection. It may take some time to get the tile ids right. Here is an example on how the tile ids work.
You can even serve tiles directly from a database.
The format leaflet specifies is very flexible.
Leaflet just uses the z,x,y place holders to request specific tiles.
For example:
L.tileLayer('http://localhost/tileserver/tile.aspx?z={z}&x={x}&y={y}', {
minZoom: 7, maxZoom: 16,
attribution: 'My Tile Server'
}).addTo(map);
where Tiles.aspx
Option Strict On
Partial Class tile
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim z, x, y As Integer
z = CInt(Request.QueryString("z"))
x = CInt(Request.QueryString("x"))
y = CInt(Request.QueryString("y"))
Dim b() As Byte = DB.GetTile(z, x, y)
Response.Buffer = True
Response.Charset = ""
'Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "image/png"
Response.AddHeader("content-disposition", "attachment;filename=" & y & ".png")
Response.BinaryWrite(b)
Response.Flush()
Response.End()
End Sub