D_DataInsightsDashboard Python GUI

👤 Sharing: AI
import tkinter as tk
from tkinter import ttk
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import seaborn as sns
import io
from tkinter import filedialog, messagebox

class DataInsightsDashboard:
    def __init__(self, master):
        self.master = master
        master.title("Data Insights Dashboard")

        self.notebook = ttk.Notebook(master)
        self.notebook.pack(fill='both', expand=True)

        self.data_tab = ttk.Frame(self.notebook)
        self.visualization_tab = ttk.Frame(self.notebook)
        self.notebook.add(self.data_tab, text='Data View')
        self.notebook.add(self.visualization_tab, text='Visualizations')

        # Data View Tab
        self.data_label = tk.Label(self.data_tab, text="Data Display:")
        self.data_label.pack(pady=10)

        self.data_text = tk.Text(self.data_tab, height=15, width=80)
        self.data_text.pack(padx=10, pady=5)

        self.load_button = tk.Button(self.data_tab, text="Load Data (CSV/Excel)", command=self.load_data)
        self.load_button.pack(pady=5)

        # Visualization Tab
        self.visualization_label = tk.Label(self.visualization_tab, text="Data Visualizations:")
        self.visualization_label.pack(pady=10)

        self.fig, self.ax = plt.subplots(figsize=(8, 6))
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.visualization_tab)
        self.canvas.get_tk_widget().pack(padx=10, pady=5)

        self.plot_type_label = tk.Label(self.visualization_tab, text="Plot Type:")
        self.plot_type_label.pack()
        self.plot_type = ttk.Combobox(self.visualization_tab, values=["Scatter", "Bar", "Hist", "Box", "Pie"])
        self.plot_type.pack()
        self.plot_type.set("Scatter") # Default

        self.x_label = tk.Label(self.visualization_tab, text="X-Axis Column:")
        self.x_label.pack()
        self.x_column = ttk.Combobox(self.visualization_tab, values=[])
        self.x_column.pack()

        self.y_label = tk.Label(self.visualization_tab, text="Y-Axis Column (optional):")
        self.y_label.pack()
        self.y_column = ttk.Combobox(self.visualization_tab, values=[])
        self.y_column.pack()

        self.generate_button = tk.Button(self.visualization_tab, text="Generate Plot", command=self.generate_plot)
        self.generate_button.pack(pady=5)

        self.details_button = tk.Button(master, text="Details", command=self.show_details)
        self.details_button.pack(pady=10)

        self.df = None

    def load_data(self):
        file_path = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv"), ("Excel files", "*.xlsx;*.xls")])
        if file_path:
            try:
                if file_path.endswith('.csv'):
                    self.df = pd.read_csv(file_path)
                else:
                    self.df = pd.read_excel(file_path)

                # Display data in the text widget
                self.data_text.delete('1.0', tk.END)
                self.data_text.insert(tk.END, self.df.to_string())

                # Update column options for visualizations
                columns = list(self.df.columns)
                self.x_column['values'] = columns
                self.y_column['values'] = columns

                messagebox.showinfo("Success", "Data loaded successfully!")

            except Exception as e:
                messagebox.showerror("Error", f"Error loading data: {e}")
        else:
            messagebox.showinfo("Info", "No file selected.")

    def generate_plot(self):
        if self.df is None:
            messagebox.showerror("Error", "No data loaded. Please load data first.")
            return

        plot_type = self.plot_type.get().lower()
        x_col = self.x_column.get()
        y_col = self.y_column.get()

        if not x_col:
            messagebox.showerror("Error", "Please select an X-Axis column.")
            return

        self.ax.clear()

        try:
            if plot_type == "scatter":
                if y_col:
                    sns.scatterplot(x=x_col, y=y_col, data=self.df, ax=self.ax)
                else:
                    sns.scatterplot(x=self.df.index, y=self.df[x_col], ax=self.ax) # Scatterplot against index if no y_col
            elif plot_type == "bar":
                sns.barplot(x=x_col, y=y_col, data=self.df, ax=self.ax)
            elif plot_type == "hist":
                sns.histplot(x=x_col, data=self.df, ax=self.ax)
            elif plot_type == "box":
                sns.boxplot(x=x_col, y=y_col, data=self.df, ax=self.ax)
            elif plot_type == "pie":
                # Pie chart requires aggregation
                counts = self.df[x_col].value_counts()
                self.ax.pie(counts, labels=counts.index, autopct='%1.1f%%', startangle=90)
                self.ax.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
            else:
                messagebox.showerror("Error", "Invalid plot type.")
                return

            self.ax.set_title(f"{plot_type.capitalize()} Plot")
            self.ax.set_xlabel(x_col)
            if y_col:
                self.ax.set_ylabel(y_col)

            self.fig.tight_layout()
            self.canvas.draw()

        except Exception as e:
            messagebox.showerror("Error", f"Error generating plot: {e}")

    def show_details(self):
        details_text = """
        **Data Insights Dashboard - Application Details**

        This application is designed to provide users with a simple and intuitive interface for exploring and visualizing data from CSV or Excel files.  It offers two main functionalities:

        1.  **Data View:**
            *   **Load Data:**  Users can load data from CSV or Excel files using the "Load Data" button.
            *   **Data Display:**  The loaded data is displayed in a text widget, allowing users to quickly inspect the raw data.

        2.  **Visualizations:**
            *   **Plot Type Selection:** Users can select from various plot types including Scatter, Bar, Histogram, Box Plot, and Pie Chart using a dropdown menu.
            *   **Axis Selection:** Users can select the columns to be used for the X and Y axes from dropdown menus that are dynamically populated based on the loaded data.
            *   **Generate Plot:**  The application generates the selected plot based on the chosen data and displays it in the visualization tab.

        **Key Features:**

        *   **User-Friendly Interface:**  A simple and intuitive GUI built with Tkinter makes the application easy to use, even for users without extensive data analysis experience.
        *   **Data Loading:** Supports loading data from both CSV and Excel files.
        *   **Interactive Visualizations:**  Allows users to easily explore data through various plot types and customize the axes.
        *   **Error Handling:** Includes robust error handling to provide informative messages to the user in case of issues.

        **Use Cases:**

        *   Quickly explore and visualize data for initial analysis.
        *   Create basic plots for presentations or reports.
        *   Gain insights from data without requiring complex data analysis tools.

        **Technical Details:**

        *   **Programming Language:** Python
        *   **GUI Library:** Tkinter
        *   **Data Analysis Libraries:** Pandas, Matplotlib, Seaborn
        """
        messagebox.showinfo("Details", details_text)

root = tk.Tk()
app = DataInsightsDashboard(root)
root.mainloop()
👁️ Viewed: 10

Comments