JFreeChart combines bar charts and line charts

Source: Internet
Author: User
In my recent work, I need to display statistical charts (based on the SSH architecture) on the Web front end. I have used JFreeChart and amchart to talk about my experiences. The biggest advantage of JFreeChart is that it can save JPG images on the Server side, and the front-end code is simple, and the compatibility of various browsers is good,... syntaxHighlighter. I recently used the JFreeChart and amchart controls to display statistical charts (based on the SSH architecture) on the Web front end.
The biggest advantage of JFreeChart is that it can save JPG images on the Server side, and the front-end code is simple, and the compatibility of various browsers is good, but the dynamic display effect is relatively poor. Amchart can better display the dynamic nature, but its shortcomings are also obvious. The front-end code is complex and cannot save server images. In addition, chrome and ff have better support for it, and the display time is very short (about 2 s), but it takes more than 30 s in ie8 (9 charts ).
JFreeChart front-end code is concise and clear, and the mid-end API is detailed. The Code is as follows:
[Javascript]
// 1. jquery calls ajax request
$ (Document). ready (function (){
$. Ajax ({
Type: "POST ",
Url: "url link to be called ",
BeforeSend: function () {// The content displayed before the call is successful
$ ("# TestImgError"). text ("getting..."); // you can use a dynamic GIF image to display the waiting process.
},
Success: function (data) {// frontend processing after successful call
$ ("# TestImgError"). text ("");
$ ("# TestImg"). attr ("src", "../test/" + data );
},
Error: function () {// handle frontend call errors
$ ("# TestImgError"). text ("Call failed ");
$ ("# TestImg"). hide ();
}
});
});
// 2. display in the front-end form. Only two lines of code can be embedded into the corresponding table or div:
 
 
  

// 3. the backend code is not complex. You need to process the data acquisition and image saving and sending processes. The Code is as follows:
// 3. 1. Data Acquisition
Public void createTestImg () throws IOException {
// Obtain the parameter. The id cannot be blank.
Integer id = Integer. parseInt (this. getRequest (). getParameter ("id "));
// Obtain data by id
List distributed = testService. getData (id );
 
ChartConstruction mtd = new ChartConstruction ("");
JFreeChart demo = mtd. getTestChart (distributed );
// Save as an image and create a folder for saving the image
String prefix = "InvestTypeDistributed -";
String path1 = "D: // Chart // paperIrrByYear ";
File newPath = new File (path1 );
If (! NewPath. exists ())
NewPath. mkdir ();
File tempFile1 = File. createTempFile (prefix, ". jpeg", newPath );
ChartUtilities. saveChartAsJPEG (tempFile1, demo, 500,270); // actual JFreeChart image Saving Method
 
// Send Json to the foreground
SendJSON (distributed );
}
//. Send Json to the foreground in a variety of ways. You can compile it as needed
Private void sendJSON (List distributed ){
Map Map = new HashMap ();
If (distributed = null) | (distributed. size () = 0 ))
Map. put ("rows", new ArrayList ());
Else
Map. put ("rows", distributed );
SenderJson (this. getResponse (), map );
}
// 3.3 organize data and form a combination of two dataset columns and line charts
Public JFreeChart getTestChart (List distributed, Integer companyId, String begin, String end ){
// List distributed = peCompanyInvestAnalysisService. getCompanyMoneyTypeDistributed (companyId, begin, end );
DefaultCategoryDataset datasetSum = new DefaultCategoryDataset ();
DefaultCategoryDataset datasetNum = new DefaultCategoryDataset ();
Double maxSum = 0.0d;
Double minSum = 0.0d;
Double tempSum = 0.0d;
Integer maxNum = 0;
Integer minNum = 0;
Integer tempNum = 0;
If (distributed! = Null)
For (int I = 0; I Map mm = (Map) distributed. get (I );
If (mm. get ("amount") = null)
TempSum = 0.0d;
Else
TempSum = Double. parseDouble (mm. get ("amount"). toString ());
If (mm. get ("num") = null)
TempNum = 0;
Else
TempNum = Integer. parseInt (mm. get ("num"). toString ());
If (tempNum = null)
TempNum = 0;

DatasetSum. addValue (tempSum, "investment currency", mm. get ("moneyType"). toString ());
DatasetNum. addValue (tempNum, "number of investment projects", mm. get ("moneyType"). toString ());
}
 
JFreeChart chart = creatChart ("investment currency distribution chart", datasetSum, datasetNum );
 
Return chart;
}
// 3.4 call the JFreeChart api to create an image Style
Private JFreeChart creatChart (String title, DefaultCategoryDataset datasetSum, defacategcategorydataset datasetNum ){
// Create a topic Style
StandardChartTheme standardChartTheme = new StandardChartTheme ("CN ");
StandardChartTheme. setExtraLargeFont (new Font ("", Font. BOLD, 15); // set the title Font
StandardChartTheme. setRegularFont (new Font ("", Font. PLAIN, 12); // set the Font of the legend
StandardChartTheme. setLargeFont (new Font ("", Font. PLAIN, 12); // set the axial Font
ChartFactory. setChartTheme (standardChartTheme); // apply the topic Style
 
JFreeChart chart = ChartFactory. createBarChart (
Title, // chart title
"", // X axis title, domain axis label
"", // Y axis title, range axis label
DatasetSum, // data
PlotOrientation. VERTICAL, // orientation
False, // include legend
True, // tooltips?
False // URLs?
);
Chart. setBackgroundPaint (Color. white );
 
CategoryPlot plot = (CategoryPlot) chart. getPlot ();
CategoryDataset categorydataset = datasetNum; // you can specify the second dataset.
Plot. setDataset (1, categorydataset );
Plot. mapDatasetToRangeAxis (1, 1 );
Plot. setBackgroundPaint (Color. white );
Plot. setRangeGridlinePaint (Color. white );
Plot. setOutlinePaint (Color. white); // set the image border Color and remove the border.
 
// Style design of the bar
BarRenderer renderer = (BarRenderer) plot. getRenderer ();
Renderer. setSeriesPaint (0, Color. orange );
Renderer. setDrawBarOutline (false );
// Set the column top data. The StandardCategoryItemLabelGenerator class does not exist in the API.
Renderer. setItemLabelGenerator (new StandardCategoryItemLabelGenerator ());
Renderer. setSeriesItemLabelsVisible (0, true );
// Avoid dynamically increasing the width of a column because the number of bars is too small (JFreeChart displays the width of a column based on the number of bars by default)
Int k = datasetSum. getColumnCount ();
If (k = 1 ){
Plot. getDomainAxis (). setLowerMargin (0.26 );
Plot. getDomainAxis (). setUpperMargin (0.66 );
} Else if (k <6 ){
Double margin = (1.0-k * 0.08)/3;
Plot. getDomainAxis (). setLowerMargin (margin );
Plot. getDomainAxis (). setUpperMargin (margin );
(BarRenderer) plot. getRenderer (). setItemMargin (margin );
} Else {
(BarRenderer) plot. getRenderer (). setItemMargin (0.1 );
}
 
/* ------ Set the Y axis ----*/
Double unit = 1d; // The Scale length.
// Right Y axis, related property settings
NumberAxis numberaxis1 = new NumberAxis ("");
Unit = Math. floor (10); // Scale Length
NumberTickUnit ntu = new NumberTickUnit (unit );
Numberaxis1.setTickUnit (ntu );
Numberaxis1.setRange (0,100); // scale range
Plot. setRangeAxis (1, numberaxis1 );
// Y axis on the left
NumberAxis numberaxis = (NumberAxis) plot. getRangeAxis ();
Numberaxis. setAutoTickUnitSelection (false );
Numberaxis. setRange (0.0, 100.0); // the range of the scale
Ntu = new NumberTickUnit (unit );
Numberaxis. setTickUnit (ntu );
/* ------ Set the upper and lower spacing between the bar and the image border ---*/
Numberaxis. setUpperMargin (0.05 );
Numberaxis. setLowerMargin (0.05 );
 
/* ------ Set the X axis ----*/
CategoryAxis domainAxis = plot. getDomainAxis ();
DomainAxis. setCategoryLabelPositions (CategoryLabelPositions. STANDARD );
/* ------ Set the tilt degree of the x-axis title ----*/
DomainAxis. setCategoryLabelPositions (CategoryLabelPositions. createUpRotationLabelPositions (Math. PI/6.0 ));
/* ------ Set the Left and Right spacing between the bar and the image border --*/
// DomainAxis. setLowerMargin (0.01 );
// DomainAxis. setUpperMargin (0.01 );
 
// Set the line chart Style
LineAndShapeRenderer lineandshaperenderer = new LineAndShapeRenderer ();
Lineandshaperenderer. setBaseItemLabelGenerator (new StandardCategoryItemLabelGenerator ());
Lineandshaperenderer. setBaseItemLabelsVisible (true );
Lineandshaperenderer. setBaseItemLabelFont (new Font ("", Font. BOLD, 10 ));
 
Plot. setRenderer (1, lineandshaperenderer );
Plot. setDatasetRenderingOrder (DatasetRenderingOrder. FORWARD );
// Legend 1 Declaration and related style settings
LegendTitle legendtitle = new LegendTitle (plot. getRenderer (0 ));
// Legend 2 Declaration and related style settings
LegendTitle legendtitle1 = new LegendTitle (plot. getRenderer (1 ));
BlockContainer blockcontainer = new BlockContainer (new BorderArrangement ());
Blockcontainer. add (legendtitle, RectangleEdge. LEFT );
Blockcontainer. add (legendtitle1, RectangleEdge. RIGHT );
Blockcontainer. add (new EmptyBlock (20D, 0.0D ));
CompositeTitle compositetitle = new CompositeTitle (blockcontainer );
Compositetitle. setPosition (RectangleEdge. BOTTOM );
Chart. addSubtitle (compositetitle );
 
Chart. setAntiAlias (false );
Chart. getRenderingHints (). put (RenderingHints. KEY_TEXT_ANTIALIASING, RenderingHints. VALUE_TEXT_ANTIALIAS_OFF );
 
Return chart;
}
 
 
 
 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.