I've developed an android application to display a pie chart. I have used the achartengine library to do this.
With this code below I get the pie chart output with 3 portions labeled as mentioned in categorySeries. I want to display the percentage values on the pie diagram. How can i do this?
public static final GraphicalView getPieChartView(Context context,
CategorySeries dataset, DefaultRenderer renderer) {
checkParameters(dataset, renderer);
PieChart chart = new PieChart(dataset, renderer);
return new GraphicalView(context, chart);
}
private static void checkParameters(CategorySeries dataset,
DefaultRenderer renderer) {
if (dataset == null
|| renderer == null
|| dataset.getItemCount() != renderer
.getSeriesRendererCount()) {
throw new IllegalArgumentException(
"Dataset and renderer should be not null and the dataset number of items should be equal to the number of series renderers");
}
}
and this is my onCreate method
Bundle bundle = getIntent().getExtras();
int highc = bundle.getInt("high");
int lowc = bundle.getInt("low");
int medc = bundle.getInt("medium");
RelativeLayout layout = (RelativeLayout) findViewById(R.id.relativestatsLayout);
TextView message = (TextView) findViewById(R.id.statText);
message.setText("\n\n\tTickets Summary");
message.setGravity(50);
//layout.addView(message);
//setContentView(message);
int[] colors = new int[] { Color.rgb(255, 0, 0),Color.rgb(220, 51,51), Color.rgb(255, 191, 0) };
DefaultRenderer renderer = buildCategoryRenderer(colors);
CategorySeries categorySeries = new CategorySeries("Tickets Chart");
categorySeries.getTitle();
categorySeries.add("critical", highc);
categorySeries.add("major ", medc);
categorySeries.add("minor ", lowc);
layout.addView(getPieChartView(this, categorySeries, renderer));
}
protected DefaultRenderer buildCategoryRenderer(int[] colors) {
DefaultRenderer renderer = new DefaultRenderer();
for (int color : colors) {
SimpleSeriesRenderer r = new SimpleSeriesRenderer();
r.setColor(color);
renderer.addSeriesRenderer(r);
}
return renderer;
}
It is possible using achartengine. I have faced the same problem and found the answer now.
Use the 1.1.0-rc2 version of achart engine. You can download it here: http://www.achartengine.org/download/
This tutorial (http://wptrafficanalyzer.in/blog/android-drawing-pie-chart-using-achartengine/) helps you to create pie chart using achartengine.
Add this line to your code to display the %of distribution in the Pie chart
defaultRenderer.setDisplayValues(true);
Reference: How to set different values for Legend and Labels in piechart While I am using Chart Engine in android
Im not sure if you still have this issue. But if your pie chart is fairly simple, you should consider drawing it your self rather using a library for it.
This might help a bit.
https://github.com/blessenm/PieChartDemo
Related
I'm currently working on functionality, that is supposed to generate stacked chart inside .pptx file.
For this I'm using code from here:
java create a chart in a powerpoint using APACHE POI
I did some modifications. Mainly I set grouping to Stacked and overlap to 100 (so the subBars looks like one bigger bar).
Now I need to display SUM of subBars values above each Bar. Aaaaand here comes my question. How can I achieve this (second pohoto below) using Apache Poi and openxmlformats.schemas.drawingml.x2006.chart?
One idea was to create another SubBar on top, make it transparent and set it's label to my desired SUM, but I cannot find a way, to set label (only Value and in this case, my transparent SubBar takes too much space and it just looks terrible - as in the photo below).
This is what I need it to look like:
I cannot find any documentation or anything apart from some threads here on StackOverflow.
Do you guys have some idea, on how to achieve this?
EDIT 1
With help from Alex I was able to print SUM values above BARs. Now I just need to get rid of these 0 values:
EDIT 2
There was a problem mentioned by Axel, that caused zeroes to be displayed (from EDIT 1). Axel edited the code in his answer, so now zeroes are gone.
How would you do that using PowerPoint? The only way I see is using a combination of stacked bar chart with line chart where the line chart displays the sum values and is set invisible. So only the data labels of the line chart are visible. The way as described in How to add total labels to stacked column chart in Excel?.
Using current apache poi 4.1.2 this can be achieved using the new XDDF stuff. For a Excel chart, I have shown that in How to generate editable Stacked-bar-chart using apache poi 4.0.1 and java?.
I will show a complete example for a PowerPoint chart as well:
import java.io.*;
import org.apache.poi.xslf.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.util.Units;
import org.apache.poi.xddf.usermodel.*;
import org.apache.poi.xddf.usermodel.chart.*;
import java.util.*;
public class CreatePowerPointStackedBarChartXDDFChart {
public static void main(String[] args) throws Exception {
try (XMLSlideShow slideShow = new XMLSlideShow()) {
XSLFSlide slide = slideShow.createSlide();
// create the data
String[] categories = new String[]{"KW1", "KW2", "KW3", "KW4", "KW5", "KW6"};
int numOfPoints = categories.length;
Double[][] values = new Double [][] {
new Double[]{10d, 0d, 20d, 5d, 30d, 10d},
new Double[]{15d, 35d, 25d, 15d, 10d, 8d},
new Double[]{5d, 15d, 0d, 25d, 15d, 0d},
new Double[]{10d, 5d, 30d, 30d, 20d, 12d}
};
Double[] sums = new Double[numOfPoints];
for (int i = 0; i < sums.length; i++) {
double sum = 0;
for (Double[] valueRow : values) {
sum += valueRow[i];
}
sums[i] = sum;
}
// create the chart
XSLFChart chart = slideShow.createChart();
// add chart to slide
slide.addChart(chart, new java.awt.geom.Rectangle2D.Double(1d*Units.EMU_PER_CENTIMETER, 1d*Units.EMU_PER_CENTIMETER, 20d*Units.EMU_PER_CENTIMETER, 15d*Units.EMU_PER_CENTIMETER));
// bar chart
// create data sources
String categoryDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, 0, 0));
XDDFDataSource<String> categoriesData = XDDFDataSourcesFactory.fromArray(categories, categoryDataRange, 0);
List<XDDFNumericalDataSource<Double>> valuesData = new ArrayList<XDDFNumericalDataSource<Double>>();
int c = 1;
for (Double[] valueRow : values) {
String valuesDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, c, c));
valuesData.add(XDDFDataSourcesFactory.fromArray(valueRow, valuesDataRange, c));
c++;
}
// create axis
XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);
leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
// Set AxisCrossBetween, so the left axis crosses the category axis between the categories.
// Else first and last category is exactly on cross points and the bars are only half visible.
leftAxis.setCrossBetween(AxisCrossBetween.BETWEEN);
// create chart data
XDDFChartData data = chart.createData(ChartTypes.BAR, bottomAxis, leftAxis);
((XDDFBarChartData)data).setBarDirection(BarDirection.COL);
// stacked bar chart
((XDDFBarChartData)data).setBarGrouping(BarGrouping.STACKED);
((XDDFBarChartData)data).setOverlap((byte)100);
// create series
if (valuesData.size() == 1) {
// if only one series do not vary colors for each bar
((XDDFBarChartData)data).setVaryColors(false);
} else {
// if more than one series do vary colors of the series
((XDDFBarChartData)data).setVaryColors(true);
}
for (int s = 0; s < valuesData.size(); s++) {
XDDFChartData.Series series = data.addSeries(categoriesData, valuesData.get(s));
series.setTitle("Series"+(s+1), chart.setSheetTitle("Series"+(s+1), s+1));
}
// plot chart data
chart.plot(data);
// add data labels
for (int s = 0 ; s < valuesData.size(); s++) {
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(s).addNewDLbls();
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(s).getDLbls()
.addNewDLblPos().setVal(org.openxmlformats.schemas.drawingml.x2006.chart.STDLblPos.CTR);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(s).getDLbls().addNewNumFmt();
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(s).getDLbls().getNumFmt()
.setSourceLinked(false);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(s).getDLbls().getNumFmt()
.setFormatCode("0;-0;");
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(s).getDLbls().addNewShowVal().setVal(true);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(s).getDLbls().addNewShowLegendKey().setVal(false);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(s).getDLbls().addNewShowCatName().setVal(false);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(s).getDLbls().addNewShowSerName().setVal(false);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(s).getDLbls().addNewShowPercent().setVal(false);
chart.getCTChart().getPlotArea().getBarChartArray(0).getSerArray(s).getDLbls().addNewShowBubbleSize().setVal(false);
}
// line chart
c = values.length + 1;
// create data source
String sumDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, c, c));
XDDFNumericalDataSource<Double> sumData = XDDFDataSourcesFactory.fromArray(sums, sumDataRange, c);
// axis must be there but must not be visible
bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
bottomAxis.setVisible(false);
leftAxis = chart.createValueAxis(AxisPosition.LEFT);
leftAxis.setVisible(false);
// set correct cross axis
bottomAxis.crossAxis(leftAxis);
leftAxis.crossAxis(bottomAxis);
data = chart.createData(ChartTypes.LINE, bottomAxis, leftAxis);
XDDFChartData.Series series = data.addSeries(categoriesData, sumData);
series.setTitle("sum", chart.setSheetTitle("sum", c));
((XDDFLineChartData.Series)series).setSmooth(false);
((XDDFLineChartData.Series)series).setMarkerStyle(MarkerStyle.NONE);
// don't show the line
XDDFShapeProperties shapeProperties = new XDDFShapeProperties();
shapeProperties.setLineProperties(new XDDFLineProperties(new XDDFNoFillProperties()));
series.setShapeProperties(shapeProperties);
// plot chart data
chart.plot(data);
// correct the id and order, must not start 0 again because there are bar series already
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).getIdx().setVal(c);
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).getOrder().setVal(c);
// add data labels
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).addNewDLbls();
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).getDLbls()
.addNewDLblPos().setVal(org.openxmlformats.schemas.drawingml.x2006.chart.STDLblPos.T);
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).getDLbls().addNewNumFmt();
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).getDLbls().getNumFmt()
.setSourceLinked(false);
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).getDLbls().getNumFmt()
.setFormatCode("0;-0;");
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).getDLbls().addNewShowVal().setVal(true);
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).getDLbls().addNewShowLegendKey().setVal(false);
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).getDLbls().addNewShowCatName().setVal(false);
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).getDLbls().addNewShowSerName().setVal(false);
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).getDLbls().addNewShowPercent().setVal(false);
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).getDLbls().addNewShowBubbleSize().setVal(false);
// Write the output to a file
try (FileOutputStream fileOut = new FileOutputStream("CreatePowerPointStackedBarChartXDDFChart.pptx")) {
slideShow.write(fileOut);
}
}
}
}
Here is a picture of the barchart. As you can see there is an alignment issue, the bars are not aligning with the labels particularly in the mid section. In addition I want the bottom Axis to show the bars in 10's not 1.2, 1.4, 1.6 etc as there will never be any decimals so its not useful. I would also like the value of each bar to be shown at the end as a number to show the total count for each bar.
Picture of chart
https://imgur.com/gallery/ThHx1eJ
Styling
// All JSON entries form the MYSQL server are parsed into an ArrayList.
moodEntries = new ArrayList<>();
// For loop which dynamically adds all entries to the ArrayList
for (MoodStatsPieChartModel moodLogPieChartResponse : moodStatsPieChartModels) {
moodEntries.add(new BarEntry(moodLogPieChartResponse.getMoodBefore(), moodLogPieChartResponse.getMoodCount()));
}
-- the .getmoodBefore() will be an int value from 1 - 18 which represents a mood
and the .getmoodCount() just totals how much of each mood.
This data is stored in the internal sqlite database.
}
// custom X-axis labels
String[] values = new String[] { "Excited", "Happy", "Confident", "Proud", "Content", "Fine", "Relaxed", "Calm", "Tired", "Guilty", "Sad", "Depressed", "Embarrassed", "Upset", "Stressed", "Anxious", "Confused", "Disgusted"};
BarDataSet barDataSet = new BarDataSet(moodEntries, "");
barDataSet.setColors(color);
barDataSet.setValueTextSize(16f);
barDataSet.setValueTextColor(Color.BLACK);
BarData data = new BarData(barDataSet);
//barData.setBarWidth(1f);
data.setValueTextSize(10f);
XAxis xAxis = chart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setLabelCount(values.length, true);
xAxis.setDrawLabels(true);
xAxis.setCenterAxisLabels(true);
xAxis.setValueFormatter(new MyXAxisValueFormatter(values));
xAxis.setGranularity(10f);
//xAxis.setGranularityEnabled(true);
//xAxis.setDrawGridLines(false);
//xAxis.setDrawAxisLine(false);
//xAxis.setDrawLabels(true);
//xAxis.setAxisMaximum(values.length);
//barChart.getXAxis().setDrawGridLines(false);
//xAxis.setAxisMinimum(values.length);
// Top Axis
YAxis yAxis = chart.getAxisLeft();
yAxis.setDrawAxisLine(false);
yAxis.setDrawGridLines(false);
//yAxis.setGranularity(1f);
yAxis.setDrawLabels(false);
//yAxis.setAxisMaximum(0f);
//yAxis.setDrawGridLinesBehindData(false);
// Bottom Axis
YAxis yAxisBottom = chart.getAxisRight();
yAxisBottom.setDrawGridLines(false);
yAxisBottom.setDrawAxisLine(false);
//yAxisBottom.setGranularity(10f);
//yAxisBottom.setDrawGridLinesBehindData(false);
//yAxisBottom.setDrawLabels(true);
//yAxisBottom.setAxisMinimum(2f);
Legend l = chart.getLegend();
l.setEnabled(false);
chart.setVisibility(View.VISIBLE);
chart.animateXY(1000, 1000);
chart.getDescription().setEnabled(false);
chart.setExtraOffsets(-10, -10, -10, -10);
chart.setDrawGridBackground(false);
chart.setDrawBarShadow(false);
chart.setDrawValueAboveBar(true);
//chart.setFitBars(true);
//chart.setMaxVisibleValueCount(100);
chart.setData(data);
chart.invalidate();
You can try this:
public class ValFormatter extends ValueFormatter {
#Override
public String getFormattedValue(float value) {
if(value == Math.round(value)){ // value is an integer?
return String.valueOf((int) value);
}else{
return "";
}
}
}
and
yAxisBottom.setValueFormatter(new ValFormatter())
Because yAxis shows you a range. This way you can fix it.
You can try these lines for value of bar:
data.setValueTextSize(10f)
data.setDrawValues(true)
Some background info: I'm creating a system to register lost, found and returned luggage. The amount of those 3 variable need to be in a LineChart to get a nice overview from how much luggage is lost etc. over an amount of time.
Now the problem:
When I create a LineChart and add it to a ChartPanel the LineChart represent a dataset. I've heard that when you edit/update your dataset, the chart is also automatically updated. Well I have an update button next to the chart which has to update the chart when clicked. Independent of the chart in an already existing JPanel/ChartPanel I also create a new frame which represent a ChartFrame.
When I click the update button a new frame pops-up and with the most recent data from the updated dataset. When I click it again, obviously another frame is created, but the already existing frame is also update while the chart in the JPanel isn't though they use the same dataset which is static and comes from a LineChart model.
Well here some code:
LineChartModel
//At the top of the document the dataset is initialize static
public static DefaultCategoryDataset dataset = null;
/*****************Other code omitted***********************/
/**
*
* Updates an already existing dataset
*
* #param dataset
* #return dataset
*/
public CategoryDataset updateDataset(DefaultCategoryDataset dataset) {
this.dataset = dataset;
// row keys...
final String rowLost = "Lost";
final String rowFound = "Found";
final String rowReturned = "Returned";
//Don't pay attention to this. It's setting the value for the dataset from different arrays which I know of the are filled correctly
int i = 0;
while (i < 12) {
dataset.setValue(lost[i], rowLost, type[i]);
System.out.println("There were " + lost[i]
+ " lost luggages in month: " + type[i]);
i++;
}
for (int j = 0; j < 12; j++) {
dataset.setValue(found[j], rowFound, type[j]);
System.out.println("There were " + found[j]
+ " found luggages in month: " + type[j]);
}
for (int j = 0; j < 12; j++) {
dataset.setValue(returned[j], rowReturned, type[j]);
System.out.println("There were " + returned[j]
+ " returned luggages in month: " + type[j]);
}
return dataset;
}
The LineChart Class with his constructor
LineChartModel model = new LineChartModel();
public ChartPanel chartPanel;
/**
* Creates a new demo.
*
* #param title the frame title.
*/
public LineChart(final String title, LineChartModel m) {
m = model;
m.selectRange();
m.createDataset();
final JFreeChart chart = createChart(m.dataset);
chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new Dimension(500, 270));
}
ChartController
First the params of the constructor
public ChartController(final ManCharts v, final LineChartModel m) {
view = v;
model = m;
And here the actionlistener of the button.
//Select a range by sumbitting the variables
v.date.btnSubmit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//selectRange select all the data between 2 dates but isn't important for this problem
m.selectRange(/*v.date.dateChooserFrom, v.date.dateChooserTo*/);
//updateDataset updates the dataset from the LineChartModel which is static
m.updateDataset(m.dataset);
//The data in the chart should already be updated but here I'm trying to replace the current chart by a new one
v.chart.chartPanel = new ChartPanel(v.chart.createChart(m.dataset));
//This is the new chart which does automatically update when the button is pressed
JFreeChart chart = ChartFactory.createLineChart("Something chart", "Date", "Value", m.dataset);
ChartFrame frame = new ChartFrame("New line chart", chart);
frame.setVisible(true);
}
});
I really hope someone can help and that this problem is not too complicated without having the full code.
If you need more code or something. Just say so.
Thanks in advance!
EDIT!
I think it has to do something with how I create the chart. The chart in my JPanel which is created at the start of my application is created with an edited method (this is part of my LineChart class and stands below my constructor):
/**
* Creates a sample chart.
*
* #param dataset a dataset.
*
* #return The chart.
*/
public JFreeChart createChart(final CategoryDataset dataset) {
// create the chart...
final JFreeChart chart = ChartFactory.createLineChart(
"Luggage", // chart title
"Time", // domain axis label
"Value", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
true, // include legend
true, // tooltips
false // urls
);
chart.setBackgroundPaint(Color.decode("#d6d9df"));
final CategoryPlot plot = (CategoryPlot) chart.getPlot();
plot.setBackgroundPaint(Color.lightGray);
plot.setRangeGridlinePaint(Color.white);
// customise the range axis...
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
rangeAxis.setAutoRangeIncludesZero(true);
// customise the renderer...
final LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
//renderer.setDrawShapes(true);
renderer.setSeriesStroke(
0, new BasicStroke(
2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
1.0f, new float[] {10.0f, 6.0f}, 0.0f
)
);
renderer.setSeriesStroke(
1, new BasicStroke(
2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
1.0f, new float[] {6.0f, 6.0f}, 0.0f
)
);
renderer.setSeriesStroke(
2, new BasicStroke(
2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
1.0f, new float[] {2.0f, 6.0f}, 0.0f
)
);
// OPTIONAL CUSTOMISATION COMPLETED.
return chart;
}
SOLVED
It had to do with another dataset that was created when clicking the submit button. So I've fixed the recreation and it's working now. Not really a chart problem, but just a problem in my model. Thanks for the help anyway!
ChartPanel implements an event listener that prompts it to repaint() itself when needed; JPanel does not. See the implementation of ChartChangeListener in chartChanged(), for example. When debugging, look for one instance of ChartPanel that shadows another or an errant use of JPanel.
Addednum Does the frame also need to be an ApplicationFrame or could it work in a JFrame?
Either is acceptable, as shown in this JFrame example or this ApplicationFrame example; both update dynamically. Note that Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
I have edited my question...
Here is the code I am using, I am adding weight of an animal with time.
else if (str.equals("Weight"))
{
mDbHelper.open();
wtArray = mDbHelper.getWeight();
mDbHelper.close();
TimeSeries diaSeries = new TimeSeries("Weight");
for ( int i =0; i <wtArray.size(); i++)
{
Weight wt = wtArray.get(i);
diaSeries.add(wt.date, wt.weight);
}
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
dataset.addSeries(diaSeries);
XYMultipleSeriesRenderer mrenderer = new XYMultipleSeriesRenderer();
XYSeriesRenderer renderer = new XYSeriesRenderer();
renderer.setColor(Color.RED);
renderer.setPointStyle(PointStyle.DIAMOND);
renderer.setFillPoints(true);
mrenderer.addSeriesRenderer(renderer);
graphLayout.addView(ChartFactory.getTimeChartView(this, dataset, mrenderer, "MM/dd/yyyy"));
}
It never shows any value on x axis, i-e time. I am using LinearLayout. Kindly tell me what is wrong. Also no Graph line is showing.
Secondly, What If I want to show data from specific date to another date?
You have two options here:
You keep using a LineChart and add custom labels while disabling the regular ones:
renderer.setXLabels(0);
renderer.addXTextLabel(date.getTime(), "Label");
You use a TimeChart which is a LineChart displaying time values using a format provided by you, instead of the LineChart.
umar.
Check my following code. I use a TimeChart here.
XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
// mDateFrom and mDateTo are Date Objects
// Set the date span here
setChartSettings(renderer, "title", "x_tiele", "y_title",
mDateFrom.getTime(),
mDateTo.getTime(), 0, 1, Color.GRAY, Color.LTGRAY);
XYMultipleSeriesDataset dataset = buildDateDataset(titles, mHashMapGroupedEntites);
return ChartFactory.getTimeChartView(context, dataset,
renderer, "yyyy/MM/dd HH"+":00:00");
Try this.
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
dataset.addSeries(diaSeries);
XYMultipleSeriesRenderer mrenderer = new XYMultipleSeriesRenderer();
mrenderer.setXAxisMin(YOUR_DATE_MIN);
mrenderer.setXAxisMax(YOUR_DATE_MAX);
// XYSeriesRenderer renderer = new XYSeriesRenderer();
mrenderer.setColor(Color.RED);
mrenderer.setPointStyle(PointStyle.DIAMOND);
mrenderer.setFillPoints(true);
// mrenderer.addSeriesRenderer(renderer);
graphLayout.addView(ChartFactory.getTimeChartView(this, dataset, mrenderer, "MM/dd/yyyy"));
I want to change the color of the "pieces" of pie in my jfreechart PieChart3D, this is the code that renders the piechart:
<% response.setContentType("image/png"); %><%#page import="org.jfree.data.general.*"%><%#page import="org.jfree.chart.*"%><%#page import="org.jfree.chart.plot.*"%><%#page import="java.awt.Color" %><%
DefaultPieDataset ds = (DefaultPieDataset)session.getAttribute("usagePieOutputDataset");
JFreeChart chart = ChartFactory.createPieChart3D
(
null, // Title
ds, // Dataset
false, // Show legend
false, // Use tooltips
false // Configure chart to generate URLs?
);
chart.setBackgroundPaint(Color.WHITE);
chart.setBorderVisible(false);
PiePlot3D plot = ( PiePlot3D )chart.getPlot();
plot.setDepthFactor(0.0);
plot.setLabelGenerator(null); //null means no labels
plot.setLabelOutlinePaint(Color.LIGHT_GRAY);
plot.setLabelFont(new java.awt.Font("Arial", java.awt.Font.BOLD, 10));
ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, 150, 144);
%>
Any help is highly appreciated.
The color for each section is normally populated from the plot's DrawingSupplier. You can override the defaults, though, by calling
PiePlot.setSectionPaint(Comparable key, Paint paint);
With, this though, you'll need to set each section manually. If you just want a different set of colors, it looks like you could implement DrawingSupplier.
You can use
Color[] colors = {Color.green, Color.red, Color.yellow .. /* size of data set */};
PieRenderer renderer = new PieRenderer(colors);
renderer.setColor(plot, ds);
and as an inner class:
static class PieRenderer
{
private Color[] color;
public PieRenderer(Color[] color)
{
this.color = color;
}
public void setColor(PiePlot plot, DefaultPieDataset dataset)
{
List <Comparable> keys = dataset.getKeys();
int aInt;
for (int i = 0; i < keys.size(); i++)
{
aInt = i % this.color.length;
plot.setSectionPaint(keys.get(i), this.color[aInt]);
}
}
}