Affichage des articles dont le libellé est pie chart. Afficher tous les articles
Affichage des articles dont le libellé est pie chart. Afficher tous les articles

Python Pie Chart Using Tkinter

How to Create a Pie Chart In Python Tkinter

How to Create a Pie Chart In Python Tkinter


In this Python tutorial we will create a pie chart using the Tkinter library for the graphical user interface. 
The pie chart displays three slices with predefined colors and values, along with a legend indicating the percentage of each slice.

What We Are Gonna Use In This Project:

- Python Programming Language.
- Tkinter for GUI.
- VS Code Editor.




Project Source Code:


import tkinter as tk
from tkinter import Canvas


class PieChart(tk.Tk):
def __init__(self):

super().__init__()
self.title("Pie Chart")
self.geometry("550x400")

# Create the PieChartPanel instance and pack it into the root window
self.pie_chart_panel = PieChartPanel(self)
self.pie_chart_panel.pack(fill=tk.BOTH, expand=True)

self.mainloop()

class PieChartPanel(Canvas):
def __init__(self, master = None):
super().__init__(master, bg="white")
# Define slice colors and data values for the pie chart
self.slice_colors = ["#FEC107", "#2196F3", "#4CAF50"]
self.data = [40, 30, 30]
# Draw the pie chart
self.draw_pie_chart()

def draw_pie_chart(self):
# Get the width and height of the canvas
width = self.winfo_reqwidth()
height = self.winfo_reqheight()
# Calculate the diameter of the pie chart
diameter = min(width, height) - 20
# Calculate the starting position of the pie chart
x = (width - diameter) / 2
y = (height - diameter) / 2
start_angle = 0

# Draw each slice of the pie chart
for i, value in enumerate(self.data):
# Calculate the angle of the current slice
arc_angle = int(value / 100 * 360)
# Draw the arc representing the slice
self.create_arc(x, y, x + diameter, y + diameter, start = start_angle,
            extent=arc_angle, fill=self.slice_colors[i], outline="black", width=2)
# Update the start angle for the next slice
start_angle += arc_angle
# Draw the legend for the pie chart
legend_x = width - 110
legend_y = 20

for i, value in enumerate(self.data):
# Draw colored rectangles representing each slice
self.create_rectangle(legend_x + 100, legend_y, legend_x + 120,
            legend_y + 20, fill=self.slice_colors[i])
# Add text indicating the percentage of each slice
self.create_text(legend_x + 130, legend_y + 10,
            text = f"Slice{i + 1}:{value}%", anchor=tk.W)
legend_y += 30



if __name__ == "__main__":
PieChart()



The Final Result:

Python Pie Chart Using Tkinter








Java Create Pie / Donut Chart

How to Create a Custom Pie and Donut Chart In Java Netbeans



In this Java Tutorial we will see How To Create a Custom Pie Chart from scratch using graphics class in java netbeans.
We Will also see how to create a donut chart.
Each chart has three slices is drawn based on the percentage data provided with custom colors (yellow, blue, green) .

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code For The Pie Chart:


package piechart;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author 1BestCsharp
 */
public class PieChart extends JFrame {
    
    private PieChartPanel pieChartPanel;
    
    public PieChart(){
        setTitle("Pie Chart");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(550,400);
        setLocationRelativeTo(null);
        
        pieChartPanel = new PieChartPanel();
        pieChartPanel.setBackground(Color.white);
        add(pieChartPanel);
        setVisible(true);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        new PieChart();
        
    }
   
}


// Panel class for displaying the pie chart
class PieChartPanel extends JPanel
{
    // Custom slice colors for the pie chart    
    private Color[] sliceColors = {Color.decode("#FEC107"),
                                   Color.decode("#2196F3"),
                                   Color.decode("#4CAF50")
                                  };
    // Initial data values representing percentages
    private int[] data = {40, 30, 30};
    
    // Override the paintComponent method to customize the drawing of the panel
    @Override
    protected void paintComponent(Graphics g){
        
        super.paintComponent(g);
        // Call the method to draw the pie chart
        drawPieChart(g);
        
    }
    
    // Method to draw the pie chart
    private void drawPieChart(Graphics g){
        // Create a Graphics2D object
        Graphics2D g2d = (Graphics2D) g;
        // Get the width of the panel
        int width = getWidth();
        // Get the height of the panel
        int height = getHeight();
        // Determine the diameter of the pie chart
        int diameter = Math.min(width, height) - 20;
        // Calculate the x-coordinate for the pie chart
        int x = (width - diameter) / 2;
        // Calculate the y-coordinate for the pie chart
        int y = (height - diameter) / 2;
        // Initialize the starting angle for the first slice of the pie chart
        int startAngle = 0;
        
        for(int i = 0; i < data.length; i++){
            // Calculate the arc angle for the current slice
            int arcAngle = (int) ((double) data[i] / 100 * 360);
            // Set the color for the current slice
            g2d.setColor(sliceColors[i]);
            // Fill the arc representing the slice
            g2d.fillArc(x, y, diameter, diameter, startAngle, arcAngle);
            // Update the starting angle for the next slice
            startAngle += arcAngle;
        }
        
        // Draw labels or legends for each slice
        // Set the x-coordinate for the legend
        int legendX = width - 110;
        // Set the initial y-coordinate for the legend
        int legendY = 20;
        
        for(int i = 0; i < data.length; i++)
        {
            // Set the color for the legend box
            g2d.setColor(sliceColors[i]);
            // Fill the legend box with color
            g2d.fillRect(legendX, legendY, 20, 20);
            // Set the text color for the legend
            g2d.setColor(Color.black);
            // Draw the legend text with slice number and percentage
            g2d.drawString("Slice " + (i + 1) + ": " + data[i] + "%", legendX + 30, legendY + 15);
            // Update the y-coordinate for the next legend entry
            legendY += 30;
        }
        
    }
    
}




   

Project Source Code For The Donut Chart:


package piechart;


import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author 1BestCsharp
 */
public class DonutChart extends JFrame {
    
    private DonutChartPanel donutChartPanel;
    
    public DonutChart(){
        setTitle("Donut Chart");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(550,400);
        setLocationRelativeTo(null);
        
        donutChartPanel = new DonutChartPanel();
        donutChartPanel.setBackground(Color.white);
        add(donutChartPanel);
        setVisible(true);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        new DonutChart();
        
    }
   
}


// Panel class for displaying the pie chart
class DonutChartPanel extends JPanel
{
    //private Color[] sliceColors = {Color.decode("#3498db"), Color.decode("#e74c3c"), Color.decode("#2ecc71")}; // Modern slice colors
    //private Color[] sliceColors = {Color.decode("#FF6B6B"), Color.decode("#74B9FF"), Color.decode("#55E6C1")}; // Custom slice colors
    private Color[] sliceColors = {Color.decode("#FF5733"), Color.decode("#33FFB2"), Color.decode("#3360FF")}; // Updated colors
    
    
    // Custom slice colors for the pie chart    
    /*private Color[] silceColors = {Color.decode("#FEC107"),
                                   Color.decode("#2196F3"),
                                   Color.decode("#4CAF50")
                                  };
*/
    // Initial data values representing percentages
    private int[] data = {75, 20, 5};
    
    // Override the paintComponent method to customize the drawing of the panel
    @Override
    protected void paintComponent(Graphics g){
        
        super.paintComponent(g);
        // Call the method to draw the pie chart
        drawDonutChart(g);
        
    }
    
    // Method to draw the pie chart
    private void drawDonutChart(Graphics g){
        // Create a Graphics2D object
        Graphics2D g2d = (Graphics2D) g;
        // Get the width of the panel
        int width = getWidth();
        // Get the height of the panel
        int height = getHeight();
        // Determine the diameter of the pie chart
        int outerDiameter = Math.min(width, height) - 20;
        int innerDiameter = outerDiameter / 2;
        // Calculate the x-coordinate for the pie chart
        int x = (width - outerDiameter) / 2;
        // Calculate the y-coordinate for the pie chart
        int y = (height - outerDiameter) / 2;
        // Initialize the starting angle for the first slice of the pie chart
        int startAngle = 0;
        
        for(int i = 0; i < data.length; i++){
            // Calculate the arc angle for the current slice
            int arcAngle = (int) ((double) data[i] / 100 * 360);
            // Set the color for the current slice
            g2d.setColor(sliceColors[i]);
            // Fill the arc representing the slice
            g2d.fillArc(x, y, outerDiameter, outerDiameter, startAngle, arcAngle);
            g2d.setColor(getBackground());
            g2d.fillArc(x+(outerDiameter - innerDiameter) / 2, y + (outerDiameter - innerDiameter) / 2, innerDiameter, innerDiameter, 0, 360);
            // Update the starting angle for the next slice
            startAngle += arcAngle;
        }
        
        // Draw labels or legends for each slice
        // Set the x-coordinate for the legend
        int legendX = width - 110;
        // Set the initial y-coordinate for the legend
        int legendY = 20;
        
        for(int i = 0; i < data.length; i++)
        {
            // Set the color for the legend box
            g2d.setColor(sliceColors[i]);
            // Fill the legend box with color
            g2d.fillRect(legendX, legendY, 20, 20);
            // Set the text color for the legend
            g2d.setColor(Color.black);
            // Draw the legend text with slice number and percentage
            g2d.drawString("Slice " + (i + 1) + ": " + data[i] + "%", legendX + 30, legendY + 15);
            // Update the y-coordinate for the next legend entry
            legendY += 30;
        }
        
    }
    
}



    



if you want the source code click on the download button below