I am trying to build a pie chart based on an array that will reflect the element, and depending on how many times it is repeated, some part of the diagram will correspond to it. I did everything according to the classics: I created a map, I write down the array element and the number of repetitions. Faced with the problem of withdrawal (see figure). The problem is that in array 1 it occurs more often, but on the diagram it corresponds to a smaller area than, for example, 5, which occurs only 1 time;
public class CreateChart extends JFrame{ public CreateChart(String appTitle, String chartTitle) { PieDataset dataset = createDataset(); JFreeChart chart = createChart(dataset,chartTitle); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(500,300)); setContentPane(chartPanel); } private PieDataset createDataset() { int[] mas = {1,1,1,2,2,4,3,2,3,4,5}; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i=0;i<mas.length;++i) { if(map.containsKey(mas[i])) { map.put(mas[i], map.get(mas[i])+1); } else {map.put(mas[i], 1);} } DefaultPieDataset result = new DefaultPieDataset(); for (Map.Entry entry : map.entrySet()) { result.setValue(entry.getKey().toString(),(int)entry.getValue()); } } private JFreeChart createChart(PieDataset dataset, String title) { JFreeChart chart = ChartFactory.createPieChart3D(title, dataset, true, true, false); PiePlot3D plot = (PiePlot3D) chart.getPlot(); plot.setStartAngle(90); plot.setDirection(Rotation.CLOCKWISE); plot.setForegroundAlpha(0.5f); return chart; } public static void main(String[] args) { CreateChart CC = new CreateChart("Pie Chart Test","OS Comparison"); CC.pack(); CC.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); CC.setVisible(true); } }
Forgot to add a picture. 1 is more common, but the area for the diagram for it is smaller
Update
I noticed an error in the rezult.setValue () method. It will be right
for (Map.Entry entry : map.entrySet()) { result.setValue(entry.getValue().toString(),(int)entry.getKey()); }
But now the chart does not display all the elements (no 4 and 5).
createDataset()
. Otherwise, the code is not compiled. What you wrote in the update is incorrect, because you have in the values - the number of repetitions, and in the keys - the values of the element of the array, the frequency of which you consider. Since the elements in the array are repeated 1, 2, or 3 times, you get 3 sectors in the diagram, and the sector value is the last key added to the data. - zRrrresult.setValue(entry.getKey().toString(),(int)entry.getKey());
, but now it can all be closed like a typo. - zRrr