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

Python Tkinter Line Chart

How to Create a Line Chart In Python Tkinter

How to Create a Line Chart In Python Tkinter


In this Python tutorial we will create a line chart using the Tkinter library for the graphical user interface. 
We will make a GUI application that displays a line chart with labeled axes and data points. 
It uses the tkinter library to draw the chart, which includes grid lines, labels, and a title. 

What We Are Gonna Use In This Project:

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




Project Source Code:


import tkinter as tk

class LineChart(tk.Canvas):
def __init__(self, master=None, **kwargs):
super().__init__(master, **kwargs)
self.padding = 30
self.label_padding = 40
self.axis_label_padding = 20
self.max_vertical_labels = 5
self.max_horizontal_labels = 5

self.vertical_labels = ["0", "25", "50", "75", "100"]
self.horizontal_labels = ["Label 1", "Label 2", "Label 3", "Label 4",
        "Label 5"]

self.draw_chart()


def draw_chart(self):
# Calculate canvas dimensions and starting points
width = self.winfo_reqwidth()
height = self.winfo_reqheight()
x_start = self.padding + self.label_padding + self.axis_label_padding
y_start = height - self.padding - self.label_padding
x_end = width - self.padding
y_end = self.padding + self.label_padding

# Calculate step size for vertical and horizontal labels
y_step = (y_start - y_end) / (self.max_vertical_labels - 1)
x_step = (x_end - x_start) / (self.max_horizontal_labels - 1)

# Draw vertical labels
for i in range(self.max_vertical_labels):
y = y_start - i * y_step
self.draw_vertical_label(self.vertical_labels[i], self.padding / 2, y)

# Draw horizontal labels
for i in range(self.max_horizontal_labels):
x = x_start + i * x_step
self.draw_horizontal_label(self.horizontal_labels[i], x,
            height - (self.padding / 2))

# Sample data
data = [50, 90, 30, 80, 10]
max_value = max(data)

# Draw the rectangle representing the chart area
self.create_rectangle(x_start, y_end, x_end, y_start, fill="white",
        outline="black")

# Draw horizontal grid lines
y_grid_count = len(self.horizontal_labels)
for i in range(y_grid_count):
y = y_start - i * y_step
self.create_line(x_start, y, x_end, y, fill="black")
# Draw vertical grid lines
x_grid_count = len(self.vertical_labels)
for i in range(x_grid_count):
x = x_start + i * x_step
self.create_line(x, y_end, x, y_start, fill="black")

# Draw data points and connecting lines
for i in range(len(data)):
# Calculate the x and y coordinates for the current data point
x = x_start + i * x_step
y = y_start - (data[i] / 100) * (y_start - y_end)
# Draw a circular data point at the calculated coordinates
self.create_oval(x-10, y-10, x+10, y+10, fill="red")

# Draw a connecting line between the current data point
            # and the previous one
if i > 0:
# Calculate the x and y coordinates for the previous data point
prev_x = x_start + (i - 1) * x_step
prev_y = y_start - (data[i - 1] / 100) * (y_start - y_end)
# Draw a line connecting the previous and current data points
self.create_line(prev_x, prev_y, x, y, width=2, fill="blue")


chart_title = "Chart Title"
self.create_text(width / 2, self.padding, text=chart_title,
            font=("Arial", 20, "bold"), fill="yellow")




def draw_vertical_label(self, label, x, y):
self.create_text(x + 30, y, text=label, fill="#ecf0f1",
        font=("Arial", 10, "bold"))
def draw_horizontal_label(self, label, x, y):
self.create_text(x, y, text=label, fill="#ecf0f1", font=("Arial", 10, "bold"))



class LineChartApp(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.line_chart = LineChart(self, width=800, height=600, background="#2c3e50")
self.line_chart.pack()


if __name__ == "__main__":
root = tk.Tk()
root.title("Line Chart")
app = LineChartApp(root)
root.mainloop()



The Final Result:

Python Tkinter Line Chart











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








Python Tkinter Animated Chart

How to Create An Animated Chart In Python Tkinter

How to Create An Animated Chart In Python Tkinter


In this Python tutorial we will create an animated bar chart using the Tkinter library for the graphical user interface. 
We will create an animated bar chart that transitions between two datasets over a specified duration.

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, StringVar
from time import sleep

class AnimatedChart(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()

self.months = ["Jan","Feb", "Mar", "Apr", "May"]
self.data1 = [00, 00, 00, 00, 00]
self.data2 = [27, 63, 47, 81, 16]
self.current_data = self.data1
self.animated_data = self.data1.copy()
self.animated_duration = 2000
self.animation_steps = 100
self.step = 0
self.chart_title = "Sales"

self.create_widgets()


def create_widgets(self):
# Create canvas
self.canvas = Canvas(self, width=600, height=450, bg="white")
self.canvas.pack()
# Start animation
self.timer_callback()
def timer_callback(self):
if self.step <= self.animation_steps:
for i in range(len(self.data1)):
# Update animated data based on current step
start_value = self.data1[i]
end_value = self.data2[i]
self.animated_data[i] = start_value + (end_value - start_value) *
                self.step / self.animation_steps

# Increment step and redraw chart
self.step += 1
self.draw_chart()
# Schedule next animation step
self.after(self.animated_duration // self.animation_steps,
            self.timer_callback)

else:
# Switch to the other set of data for the next animation cycle
self.current_data = self.data2 if self.current_data == self.data1
            else self.data1
self.step = 0



def draw_chart(self):
# Clear canvas
self.canvas.delete("all")

# Set chart dimensions
chart_width = 600
chart_height = 400
bar_spacing = 30
bar_width = (chart_width - (len(self.current_data) + 1) * bar_spacing) /
        len(self.current_data)

# Draw chart title
self.canvas.create_text(chart_width // 2, 30, text=self.chart_title,
        font=("Arial", 28, "bold"), fill="blue")

# Draw horizontal grid lines
for i in range(1, 26):
y = chart_height - i * (chart_height - 100) /25 - 20
self.canvas.create_line(bar_spacing, y, chart_width - bar_spacing, y,
            fill="#e0e0e0")


# Draw vertical grid lines
for i in range(len(self.current_data) + 1):
x = bar_spacing + i * (bar_width + bar_spacing) + bar_width / 2
self.canvas.create_line(x, chart_height - 20, x, 80, fill="#e0e0e0")


# Draw bars and labels
for i in range(len(self.current_data)):
bar_height = (self.animated_data[i] / 100) * (chart_height - 100)
x = bar_spacing + i * (bar_width + bar_spacing)
y = chart_height - bar_height - 20

# Draw bar
self.canvas.create_rectangle(x, y, x + bar_width, chart_height - 20,
            fill="#6a1b9a")

# Draw month label
self.canvas.create_text(x + bar_width / 2, chart_height - 5,
            text = self.months[i], font=("Arial", 12), fill="black")
# Draw bar value label
self.canvas.create_text(x + bar_width / 2, y - 10,
            text = str(int(self.animated_data[i])), font=("Arial", 14), fill="black")


if __name__ == "__main__":
root = tk.Tk()
root.title("Animated Chart")
app = AnimatedChart(master=root)
root.mainloop()


The Final Result:

Python Tkinter Animated Chart











Python Tkinter 3D Bar Chart

How to Create a 3D Bar Chart In Python Tkinter

Python Tkinter 3D Bar Chart


In this Python tutorial we will create a 3D bar char using the Tkinter library for the graphical user interface. 
Each bar features a distinct front, top, and side face, creating a three-dimensional appearance.

What We Are Gonna Use In This Project:

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




Project Source Code:


import tkinter as tk
import random

class ThreeDBarChartPanel(tk.Canvas):

def __init__(self, master=None, **kwargs):
# Initialize the ThreeDBarChartPanel as a Canvas
super().__init__(master, **kwargs)
# Bar Colors
self.color_side_face = "#2c3e50"
self.color_top_face = "#e74c3c"
self.color_front_face = "#3498db"
# Draw the 3D bar chart
self.draw_chart()

def draw_chart(self):
width = self.winfo_reqwidth()
height = self.winfo_reqheight()
num_bars = 10
bar_width = 40
bar_spacing = 30

base_x = (width - (num_bars * (bar_width + bar_spacing) - bar_spacing)) /2
base_y = height - 100

labels = [f"label{i}" for i in range(1, num_bars + 1)]

# Draw horizontal lines for reference
num_horizontal_lines = 5
horizontal_spacing = (base_y - 50) // num_horizontal_lines

for i in range(num_horizontal_lines + 1):
y = base_y - i * horizontal_spacing
#self.create_line(30, y, width - 20, y, fill="lightgray", dash=(2,2))
self.create_line(30, y, width - 20, y, fill="lightgray")

# Draw Bars
for i in range(num_bars):
x = base_x + i * (bar_width + bar_spacing)
bar_height = random.randint(50, 250)
z = 10

# Draw the front face of the bar
self.create_rectangle(x, base_y - bar_height, x + bar_width, base_y,
            fill=self.color_front_face)

# Draw the top face of the bar
top_face = [ x, base_y - bar_height, x + bar_width, base_y-bar_height,
            x + bar_width + z, base_y - bar_height-z, x + z, base_y - bar_height-z ]
self.create_polygon(top_face, fill=self.color_top_face)

# Draw the side face of the bar
side_face = [ x + bar_width, base_y - bar_height, x + bar_width, base_y,
            x + bar_width + z, base_y - z, x + bar_width + z, base_y - bar_height-z ]
self.create_polygon(side_face, fill=self.color_side_face)

# Draw vertical axis labels
axis_label_x = x + bar_width / 2
axis_label_y = base_y + 20
self.create_text(axis_label_x, axis_label_y, text=labels[i])


# Draw horizontal axis labels
num_ticks = 5
tick_spacing = (base_y - 50) / num_ticks
self.create_text(base_x - 20, base_y - 5, text="0")

for i in range(1, num_ticks + 1):
tick_value = 40 + i * 40
self.create_text(base_x - 30, base_y - i * tick_spacing,
            text = str(tick_value))



class ThreeDBarChartApp:
def __init__(self, root):
self.root = root
self.root.title("3D Bar Chart")
self.root.geometry("800x500")
self.root.resizable(False, False)

# Create and pack the ThreeDBarChartPanel
self.chartPanel = ThreeDBarChartPanel(self.root, bg="white", width="800",
        height="400")
self.chartPanel.pack(expand=True, fill="both")



if __name__ == "__main__":
root = tk.Tk()
app = ThreeDBarChartApp(root)
root.mainloop()


The Final Result:

How to Create a 3D Bar Chart In Python Tkinter








Java Create Line Chart

How to Create a Custom Line Chart In Java Netbeans

How to Create a Custom Line Chart In Java Netbeans


In this Java Tutorial we will see How To Create a Custom Line Chart from scratch with labeled axes, grid lines, and data points using graphics class and jpanel in java netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code:


package linechart;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import javax.swing.JFrame;
import javax.swing.JPanel;


/**
 *
 * @author 1BestCsharp
 */
public class LineChart extends JPanel{

    // Constants for padding and labels
    private final int padding = 30;
    private final int labelPadding = 40;
    private final int axisLabelPadding = 20;
    private final int maxVerticalLabels = 5;
    private final int maxHorizontalLabels = 5;
    
    // Arrays for vertical and horizontal labels
    private String[] verticalLabels = {"0","25","50","75","100"};
    private String[] horizontalLabels = {"Label 1","Label 2","Label 3","Label 4","Label 5"};
    
    @Override
    protected void paintComponent(Graphics g){
        
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        
        // Calculate coordinates and dimensions
        int width = getWidth();
        int height = getHeight();
        int xStart = padding + labelPadding + axisLabelPadding;
        int yStart = height - padding - labelPadding;
        int xEnd = width - padding;
        int yEnd = padding + labelPadding;
        
        // Calculate step size for vertical and horizontal labels
        int yStep = (yStart - yEnd) / (maxVerticalLabels - 1);
        int xStep = (xEnd - xStart) / (maxHorizontalLabels - 1);
        
        // Draw vertical labels
        for(int i = 0; i < maxVerticalLabels; i++){
            int y = yStart - i * yStep;
            drawVerticalLabel(g2d, verticalLabels[i], padding / 2, y);
        }
        
        // Draw horizontal labels
        for(int i = 0; i < maxHorizontalLabels; i++){
            int x = xStart + i * xStep;
            //drawHorizontal(g2d, horizontalLabels[i], x, height - (padding / 2));
            drawHorizontalLabel(g2d, horizontalLabels[i], x, height - (padding / 2));
        }
        
        // Data for the chart
        int[] data = {40, 100, 75, 20, 55};
        int maxValue = 100;
        
        // Find the maximum value in the data
        for(int value : data){
            if(value > maxValue)
            {
                maxValue = value;
            }
        }
        
        // Draw chart background
        g2d.setColor(Color.white);
        g2d.fillRect(xStart, yEnd, xEnd - xStart, yStart - yEnd);
        
        // Draw chart border
        g2d.setColor(Color.black);
        g2d.drawRect(xStart, yEnd, xEnd - xStart, yStart - yEnd);
        
        // Draw horizontal grid lines
        int yGridCount = 5;
        for(int i = 0; i < yGridCount; i++){
            int y = yStart - i * yStep;
            g2d.setColor(Color.red);
            g2d.drawLine(xStart, y, xEnd, y);
        }
        
        // Draw vertical grid lines
        int xGridCount = data.length;
        for(int i = 0; i < xGridCount; i++){
            int x = xStart + i * xStep;
            g2d.setColor(Color.lightGray);
            g2d.drawLine(x, yEnd, x, yStart);
        }
        
        
        // Plot data points and connect with lines
        for(int i = 0; i < data.length; i++){
            g2d.setColor(Color.orange);
            int x = xStart + i * xStep;
            int y = yStart - data[i] * (yStart - yEnd) / maxValue;
            g2d.fillOval(x-5, y-5, 10, 10);
            
            // Connect data points with lines
            if( i > 0){
                int prevX = xStart + (i - 1) * xStep;
                int prevY = yStart - data[i - 1] * (yStart - yEnd) / maxValue;
                g2d.setStroke(new BasicStroke(2));
                g2d.setColor(Color.gray);
                g2d.drawLine(prevX, prevY, x, y);
            }
        }
        
        // Draw Chart Title
        g2d.setFont(new Font("Arial",Font.BOLD, 20));
        g2d.setColor(Color.red);
        String chartTitle = "Chart Title";
        g2d.drawString(chartTitle, (width - g2d.getFontMetrics().stringWidth(chartTitle)) / 2, padding);        
    }
    
    // Method to draw a vertical label with rotation
    private void drawVerticalLabel(Graphics2D g2d, String label, int x, int y){
        AffineTransform atf = new AffineTransform();
        atf.rotate(-Math.PI / 2);
        Font rotatedFont = g2d.getFont().deriveFont(atf);
        g2d.setFont(rotatedFont);
        g2d.setColor(Color.yellow);
        g2d.drawString(label, x + 30, y);
        g2d.setFont(g2d.getFont().deriveFont(atf));
    }
    
    // Method to draw a horizontal label
    private void drawHorizontalLabel(Graphics2D g2d, String label, int x, int y){
        g2d.setColor(new Color(248,239,186));
        g2d.drawString(label, x - g2d.getFontMetrics().stringWidth(label) / 2, y);
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        JFrame frame = new JFrame();
        frame.setTitle("Custom Line Chart");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        LineChart chartPanel = new LineChart();
        chartPanel.setBackground(Color.darkGray);
        frame.add(chartPanel);
        frame.setVisible(true);
        
    }

}




The Final Result:

Java Line Chart

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