Pie Chart Responses from SUSI Server
Giving out responses in charts and graphs is a very common reply of various assistants. We also have it in SUSI. We can show users the output of stocks, market covers and various percentages output in Pie Charts.
A pie chart is a circular chart/graph which is divided in some segments like a pie. The segments in a pie chart shows the share of each object or category.
The PieChartServlet in SUSI Server is a servlet that takes the JSON data of a the pie chart components as input parameters and returns an Image of the rendered Pie Chart..
public class PieChartServlet extends HttpServlet {
This is a simple HttpServlet. It does not require any authentication or base user role. So we extend the HttpServlet here.
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
doGet is a method which is triggered whenever the PieChartServlet receives a GET Query. This will contain all the code that we will need to render the final output.
{"ford":"17.272992","toyota":"27.272992","renault":"47.272992"}
This is the sample JSON that we send to the PieChartServlet. This contains the names of the pie chart components and their respective percentages. After we receive these parameters we parse them and store them in our local variables.
These variables are then further used to plot the pie chart.
To plot these values in pie chart we have used a library JFreeChart.
This is a free and well documented Java chart library. This library supports PNGs and JPEGs as well as vector graphics file formats
JFreeChart chart = getChart(json, legendBit, tooltipBit);
From here we call a function getChart This function accept 3 parameters. The json which we sent as the GET parameter, legendBit and tooltilBit. These are also sent as GET parameters. In this example I will use legendBit as true and tooltipBit as false.
JFreeChart chart = ChartFactory.createPieChart("SUSI Visualizes - PieChart", dataset, legend, tooltips, urls); chart.setBorderPaint(Color.BLACK); chart.setBorderStroke(new BasicStroke(5.0f)); chart.setBorderVisible(true); return chart;
This is the function getChart. It creates a chart using the ChartFactory method and set sets the SUSI branding on it as “SUSI Visualizes – PieChart”. It accepts the datasets, legends and tool tips. The variable, dataset is nothing but the json keys and their values.
After the ChartFactory returns the chart we set the border of the chart and returns a pie chart back the function where it was called.
ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
Finally we write the chart as a PNG image and send it to the user.
Output
This can be tested at
References
- JFreeChart Homepage: http://www.jfree.org/jfreechart/
- JFreeChart Documentation: http://www.jfree.org/jfreechart/api/javadoc/index.html
- SUSI Server: https://github.com/fossasia/susi_server/