Open In App

Visualizing bar plot and Line plot with Kivy

Last Updated : 14 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Kivy is a Python framework that simplifies building interactive applications with multi-touch capabilities useful for creating dynamic visualizations. This article will explain how to visualize data using bar and line plots in Kivy, providing a quick example to illustrate the concepts.

Setting Up Kivy Environment

Before diving into data visualization with Kivy, it's essential to set up the development environment correctly. This section provides a step-by-step guide to installing Kivy and preparing your system for building visualization applications.

  • Python : Make sure you have Python (3.7 version or later) installed on your machine.
  • Kivy supports Python versions from 3.7 onwards.

Installation Steps:

  • Create a Virtual Environment (Optional but Recommended):
  • python -m venv kivy_env
    source kivy_env/bin/activate # On Windows: kivy_env\Scripts\activate

Install Kivy:

  • The [base] includes the core dependencies.
  • kivy_examples provides example applications which are useful for learning.
pip install kivy[base] kivy_examples

1. Bar Plot with Kivy

We can specify the x and y data points representing categories and their corresponding values. The bars heights correspond to the values provided in the dataset.

Python
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Rectangle, Color
from kivy.uix.boxlayout import BoxLayout
from kivy.core.window import Window

class BarChartWidget(Widget):
    def __init__(self, **kwargs):
        super(BarChartWidget, self).__init__(**kwargs)
        self.data = [30, 70, 45, 90, 60]
        self.draw_bars()

    def draw_bars(self):
        with self.canvas:
            Color(0.2, 0.6, 0.86, 1) 
            bar_width = Window.width / (len(self.data) * 2)
            spacing = bar_width
            for index, value in enumerate(self.data):
                x = spacing + index * (bar_width + spacing)
                y = 50
                Rectangle(pos=(x, y), size=(bar_width, value))

class BarChartApp(App):
    def build(self):
        layout = BoxLayout()
        bar_chart = BarChartWidget()
        layout.add_widget(bar_chart)
        return layout

if __name__ == '__main__':
    BarChartApp().run()

Execute the Script in the terminal

python bar_chart.py

Output:

Screenshot-2025-01-10-170051
Barchart in kivy

This is the output of the bar chart code in Kivy. It displays bars with heights corresponding to the data values provided in the code. Each bar is evenly spaced and drawn using Kivy’s canvas graphics, demonstrating a simple way to visualize data in a chart format

2. Interactive Line Chart with Touch Events

Interactivity elevates data visualization from static charts to engaging tools that allow users to explore data dynamically. Kivy's event handling and widget system make it feasible to implement interactive features such as tooltips, zooming, and real-time data updates.

Let's create an interactive line chart where users can tap on data points to view details.

Python
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Line, Color, Ellipse
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from kivy.uix.label import Label

class InteractiveLineChart(Widget):
    def __init__(self, **kwargs):
        super(InteractiveLineChart, self).__init__(**kwargs)
        self.data = [10, 20, 15, 30, 25, 35, 20]
        self.points = []
        self.draw_line()

    def draw_line(self):
        with self.canvas:
            Color(0.8, 0.3, 0.3, 1)  # Line color
            self.line = Line(points=self.get_line_points(), width=2)
            Color(0, 0, 0, 1)  # Point color
            for point in self.points:
                Ellipse(pos=point, size=(10, 10))

    def get_line_points(self):
        width, height = self.size
        padding = 50
        max_value = max(self.data)
        points = []
        self.points = []
        for index, value in enumerate(self.data):
            x = padding + index * ((width - 2 * padding) / (len(self.data) - 1))
            y = padding + (value / max_value) * (height - 2 * padding)
            points.extend([x, y])
            self.points.append((x - 5, y - 5))  
        return points

    def on_touch_down(self, touch):
        for index, point in enumerate(self.points):
            x, y = point
            if x <= touch.x <= x + 10 and y <= touch.y <= y + 10:
                self.show_popup(index)
                return True
        return super(InteractiveLineChart, self).on_touch_down(touch)

    def show_popup(self, index):
        popup = Popup(title=f'Data Point {index + 1}',
                      content=Label(text=f'Value: {self.data[index]}'),
                      size_hint=(None, None), size=(200, 200))
        popup.open()

    def on_size(self, *args):
        self.canvas.clear()
        self.draw_line()

class LineChartApp(App):
    def build(self):
        layout = BoxLayout()
        chart = InteractiveLineChart()
        layout.add_widget(chart)
        return layout

if __name__ == '__main__':
    LineChartApp().run()

Execute the script

python interactive_line_chart.py
Screenshot-2025-01-10-170406
Line chart with Kivy


This code creates a simple interactive line chart. It draws a line connecting data points, displays dots for each point, and lets users tap on a dot to see its value in a popup. It also adjusts the chart automatically if the window size change


Next Article
Article Tags :

Similar Reads