### Install sjvisualizer with pip Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/README.md Use pip to install the sjvisualizer library. This is the first step before using any of its functionalities. ```bash pip install sjvisualizer ``` -------------------------------- ### Initialize and Play Visualization Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/StaticText.html Example of initializing the Canvas and DataHandler, creating a static text element, adding it to the canvas, and playing the visualization. ```python if __name__ == "__main__": from sjvisualizer import Canvas, DataHandler df = DataHandler.DataHandler(excel_file="data/Neg Number Bar Dev.xlsx", number_of_frames=0.25*60*60).df canvas = Canvas.canvas() bar_chart = static_text(canvas=canvas, text="test", df=df, font_size=50, text_font="Georgia") canvas.add_sub_plot(bar_chart) canvas.play(fps=60, record=False) ``` -------------------------------- ### Initialize and Play Bar Race Visualization Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/BarRace.html Sets up the DataHandler, Canvas, and BarRace object, then starts the visualization playback. This is the main entry point for running the bar race. ```python if __name__ == "__main__": from sjvisualizer import Canvas, DataHandler df = DataHandler.DataHandler(excel_file="data/Neg Number Bar Dev.xlsx", number_of_frames=0.25*60*60).df canvas = Canvas.canvas() bar_chart = bar_race(canvas=canvas, df=df, decimal_places=3) canvas.add_sub_plot(bar_chart) canvas.play(fps=60, record=False) ``` -------------------------------- ### Create Multi-Chart Dashboard Example Source: https://context7.com/sjoerdtilmans/sjvisualizer/llms.txt Demonstrates creating complex visualizations with multiple chart types, including bar and pie charts, titles, and time indicators. ```python from sjvisualizer import Canvas, DataHandler, BarRace, PieRace, Date, StaticText import json def create_dashboard(): # Load data df = DataHandler.DataHandler( excel_file="data/browsers.xlsx", number_of_frames=60 * 60 * 0.5 ).df # Load or define colors colors = { "Chrome": [66, 133, 244], "Safari": [0, 122, 255], "Firefox": [255, 87, 34], "Edge": [0, 120, 212], "Opera": [255, 26, 26], "Other": [150, 150, 150] } # Create canvas canvas = Canvas.canvas(bg=(250, 250, 250)) # Add bar chart on the left bar_chart = BarRace.bar_race( canvas=canvas, df=df, colors=colors, width=600, height=500, x_pos=50, y_pos=150, number_of_bars=6, font_color=(50, 50, 50), unit="%" ) canvas.add_sub_plot(bar_chart) # Add pie chart on the right pie_chart = PieRace.pie_plot( canvas=canvas, df=df, colors=colors, width=600, height=500, x_pos=700, y_pos=150, font_color=(50, 50, 50), sort=True ) canvas.add_sub_plot(pie_chart) # Add title canvas.add_title( text="Browser Market Share Dashboard", color=(30, 30, 30) ) # Add date indicator canvas.add_time(df=df, time_indicator="month", color=(100, 100, 100)) # Play animation canvas.play(fps=60, record=True, file_name="dashboard.mp4") if __name__ == "__main__": create_dashboard() ``` -------------------------------- ### Initialize and Run Bubble Chart Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/Bubble.html Example demonstrating how to initialize a BubbleChart instance with data handlers, canvas, and custom colors, then add it to the canvas and play the animation. ```python if __name__ == "__main__": from sjvisualizer import Canvas, DataHandler df_y = DataHandler.DataHandler(excel_file="data/Y_log.xlsx", number_of_frames=60*15).df df_x = DataHandler.DataHandler(excel_file="data/X_log.xlsx", number_of_frames=60*15).df df_size = DataHandler.DataHandler(excel_file="data/X2 - Copy.xlsx", number_of_frames=60*15).df canvas = Canvas.canvas() colors = { "Neg column": (255, 0, 0) } dc = bubble_chart(canvas=canvas, colors=colors, y_log=True, x_log=True, df_x=df_x, df_y=df_y, df_size=df_size, font_size=25, font_color=(0, 0, 0)) canvas.add_sub_plot(dc) canvas.play(fps=60, record=False) ``` -------------------------------- ### DynamicMatrix.draw Method Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/index.html Executes the initial drawing of the animation at the start. ```APIDOC ## DynamicMatrix.draw ### Description This function is executed once at the start of the animation to draw the initial state. ### Parameters - **time** (any) - The current time or frame identifier. ``` -------------------------------- ### Initialize DynamicLine with Custom Data Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/DynamicLine.html This example demonstrates initializing the dynamic_curve class, which is used for custom data animations. It sets up the canvas, dimensions, data source (pandas DataFrame), and visual properties like color, font, and marker size. ```python from sjvisualizer import Canvas as cv from sjvisualizer import Axis from sjvisualizer.Canvas import from tkinter import from PIL import Image import io import datetime import time import math from PIL import Image, ImageTk import copy import pandas as pd from tkinter import font import random import operator import os import ctypes import json import platform from screeninfo import get_monitors months = 1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sept", 10: "Oct", 11: "Nov", 12: "Dec", } random_colors = (102,155,188), (168,198,134), (243,167,18), (41,51,92), (228,87,46), (255,155,113), (255,253,130), (45,48,71), (237,33,124), (27,153,139), (245,213,71), (219,48,105), (20,70,160), (0,0,200), (0,200,0), (200,0,0), (66,217,200), (44,140,153), (50,103,113), (40,70,75), (147,22,33), (208,227,127), (221,185,103), (209,96,61), (34,29,35), (97,87,113), (81,70,99), (77,83,130), (202,207,133), (140,186,128), (101,142,156) if platform.system() == "Windows": SCALEFACTOR = ctypes.windll.shcore.GetScaleFactorForDevice(0) / 100 elif platform.system() == "Darwin": # if OS is mac SCALEFACTOR = 1 elif platform.system() == "Linux": # if OS is linux SCALEFACTOR = 1 else: # if OS can't be detected SCALEFACTOR = 1 format_str = '%d-%m-%Y' # The format monitor = get_monitors()[0] HEIGHT = monitor.height WIDTH = monitor.width class dynamic_curve(cv.sub_plot): """Example class to create custom data animations this class is derived from the sub_plot class :param canvas: tkinter canvas to draw the graph to :type canvas: tkinter.Canvas :param width: width of the plot in pixels, default depends on screen resolution :type width: int :param height: height of the plot in pixels, default depends on screen resolution :type height: int :param x_pos: the x location of the top left pixel in this plot, default depends on screen resolution :type x_pos: int :param y_pos: the y location of the top left pixel in this plot, default depends on screen resolution :type y_pos: int :param df: pandas dataframe that holds the data :type df: pandas.DataFrame :param color: list or tuple holding rgb color value for the line, default is (31, 119, 180) :type colors: list :param font_color: font color, default is (0,0,0) :type font_color: tuple of length 3 with integers :param font_size: font size, in pixels :type font_size: int :param unit: unit of the values visualized, default is "" :type unit: str :param text_font: selected font, defaults to Microsoft JhengHei UI :type text_font: str :param marker_size: size of the markers :type marker_size: int """ def draw(self, time): """This function gets executed only once at the start of the animation""" self.default_min_value = 0 if not hasattr(self, "marker_size"): self.marker_size = 15 if not hasattr(self, "color"): self.color = (31, 119, 180) # get the data for the given time step data = self._get_data_for_frame(time) # create a dictionary to hold all graph_element objects self.graph_elements = {} # create axis self.axis = Axis.axis(canvas=self.canvas, n=self.y_ticks, orientation="vertical", x=self.x_pos, y=self.y_pos + self.height*0.85, length=self.height*0.85, width=self.width, allow_decrease=False, is_date=False, font_size=self.font_size, color=self.font_color, ticks_only=False, unit=self.unit) self.axis.draw(min=min(data), max=max(data)) # create line object self.line = self.canvas.create_line(0,0,0,0, fill=cv._from_rgb(self.color), width=int(self.marker_size/3)) # loop over all values in the row spacing = self.width / (len(data)) x_pos = self.x_pos + spacing / 2 for i, (name, d) in enumerate(data.items()): ``` -------------------------------- ### sjvisualizer.Bubble.bubble_chart.draw Method Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/Bubble.html This function gets executed only once at the start of the animation to set up the bubble chart. ```APIDOC ## sjvisualizer.Bubble.bubble_chart.draw Method ### Description This function gets executed only once at the start of the animation. ### Method `draw(self, time)` ### Parameters - **time** (any) - The current time step for which to draw the data. ``` -------------------------------- ### sjvisualizer.DynamicLine.dynamic_curve.draw Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/DynamicLine.html This function gets executed only once at the start of the animation to draw the initial graph elements. ```APIDOC ## sjvisualizer.DynamicLine.dynamic_curve.draw ### Description This function gets executed only once at the start of the animation. ### Method GET ### Endpoint None (This is a method within a class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **time** (any) - Required - The time step for which to get the data. ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Initialize and Play Sjvisualizer Dynamic Matrix Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/DynamicMatrix.html Sets up the Sjvisualizer environment by loading data, creating a canvas, initializing a DynamicMatrix chart, and then playing the visualization with specified frames per second. ```python if __name__ == "__main__": from sjvisualizer import Canvas, DataHandler df = DataHandler.DataHandler(excel_file="data/DynamicMatrix.xlsx", number_of_frames=60*10).df canvas = Canvas.canvas() empty_chart = dynamic_matrix(canvas=canvas, font_size=25, df=df, neutral_string="Neutral", level_count=3) canvas.add_sub_plot(empty_chart) canvas.add_time(df=df, time_indicator="day") canvas.add_title("Dynamic Matrix") canvas.play(fps=60) ``` -------------------------------- ### DynamicMatrix Draw Method Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/index.html The draw function is executed once at the start of the animation. ```python draw(_time_) ``` -------------------------------- ### sjvisualizer.DynamicMatrix.draw Method Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/DynamicMatrix.html The draw method is executed once at the start of the animation to set up the graph elements. ```APIDOC ## POST /sjvisualizer.DynamicMatrix.draw ### Description This function gets executed only once at the start of the animation. ### Method POST ### Endpoint /sjvisualizer.DynamicMatrix.draw ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **time** (any) - The time step for which to get the data. ### Request Example ```json { "time": "example_time_step" } ``` ### Response #### Success Response (200) * **graph_elements** (dict) - A dictionary holding all graph_element objects. * **spacing** (float) - The calculated spacing for the plot elements. * **neutral_string** (str) - The string used to represent neutral values. * **font_size** (int) - The font size used for text elements. * **level_count** (int) - The number of discrete sentiment levels. * **color_range** (list) - The color range used for sentiment visualization. * **max_label_width** (int) - The maximum width of any label in the plot. #### Response Example ```json { "graph_elements": {}, "spacing": 10.5, "neutral_string": "0", "font_size": 12, "level_count": 2, "color_range": [[255, 40, 60], [3, 175, 81]], "max_label_width": 50 } ``` ``` -------------------------------- ### Main Execution Block for sjvisualizer Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/Histogram.html Demonstrates how to initialize and run the sjvisualizer, including loading data, creating a canvas, adding a histogram, and playing the animation. ```python if __name__ == "__main__": from sjvisualizer import Canvas, DataHandler df = DataHandler.DataHandler(excel_file="data/Area Dev.xlsx", number_of_frames=60*30).df canvas = Canvas.canvas() eq = histogram(canvas=canvas, df=df, font_size=25, font_color=(0, 0, 0)) canvas.add_sub_plot(eq) canvas.play(fps=60) ``` -------------------------------- ### sjvisualizer.Histogram.draw Method Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/Histogram.html The draw method is executed once at the start of the animation to set up and draw the histogram. ```APIDOC ## sjvisualizer.Histogram.draw Method ### Description This function gets executed only once at the start of the animation. ### Parameters - **time** - The current time step for which to get data. ``` -------------------------------- ### Initialize and Play Sjvisualizer Canvas Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/LineChart.html Demonstrates the main execution block for Sjvisualizer. Initializes DataHandler and Canvas, creates a LineChart instance, adds it to the canvas, and plays the animation. ```python if __name__ == "__main__": from sjvisualizer import Canvas, DataHandler df = DataHandler.DataHandler(excel_file="data/Neg Number Bar Dev.xlsx", number_of_frames=0.25*60*60).df canvas = Canvas.canvas() line_chart = line_chart(canvas=canvas, text="test", df=df, font_size=50, text_font="Georgia") canvas.add_sub_plot(line_chart) canvas.play(fps=60, record=False) ``` -------------------------------- ### sjvisualizer.BarRace.draw Method Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/BarRace.html The draw method is executed once at the start of the animation to set up the initial state of the bar race chart. ```APIDOC ## sjvisualizer.BarRace.draw Method ### Description This function gets executed only once at the start of the animation to draw the initial state of the bar race chart. ### Method POST (Implicitly called by the animation loop) ### Endpoint N/A (This is a method within a class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **time** (any) - Required - The current time step or frame identifier for which to draw the data. ### Request Example ```json { "time": "2023-10-27T10:00:00Z" } ``` ### Response #### Success Response (200) * **None** - This method does not return a value. It modifies the canvas by drawing graph elements. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Main Execution Block for SJVisualizer Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/DynamicLine.html Sets up and runs the SJVisualizer with sample data, creating a canvas, initializing a dynamic curve, adding it to the canvas, and playing the animation. ```python if __name__ == "__main__": from sjvisualizer import Canvas, DataHandler df = DataHandler.DataHandler(excel_file="data/Area Dev.xlsx", number_of_frames=60*30).df canvas = Canvas.canvas() dc = dynamic_curve(canvas=canvas, df=df, font_size=25, font_color=(0, 0, 0)) canvas.add_sub_plot(dc) canvas.play(fps=60) ``` -------------------------------- ### DynamicMatrix Color Bar Color Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/index.html Specifies the start and end colors for the color bar using a list of RGB lists. ```python color_bar_color=[[210,210,210], [100,40,10]] ``` -------------------------------- ### Load Data from Cache Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/DataHandler.html Loads a pandas DataFrame from a cached Excel file. It also removes any columns that start with 'Unnamed'. ```python def _load_file(self): self.df = pd.read_excel(self.cache_location, index_col=[0]) self.df = self.df.loc[:, ~self.df.columns.str.contains('^Unnamed')] ``` -------------------------------- ### Initialize Color Bar Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/WorldMap.html Sets up a color bar object with canvas, color gradient, coordinates, data, unit, minimum value, font color, and decrease allowance. ```python def __init__(self, canvas, colors, x1, y1, x2, y2, data, unit="", min_value=0, font_color=(0, 0, 0), allow_decrease=False, parent=None): self.canvas = canvas self.colors = colors self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 self.unit = unit ``` -------------------------------- ### Initialize Bar Element Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/BarRace.html Initializes a bar element for the visualization. Sets up physics properties, loads an image if available, and determines the bar's color. ```python def __init__(self, name=None, canvas=None, value=0, font_color=(0,0,0), colors={}, font_size=12, chart=None, text_font="Microsoft JhengHei UI", bar_height=50, unit=""): self.name = name self.canvas = canvas self.unite = unit self.font_color = font_color self.font_size = font_size self.chart = chart self.colors = colors self.text_font = text_font self.exists = False self.bar_height = bar_height self.unit = unit self.mass = 2 self.stiffness = 0.1 self.damping = 0.6 self.v = 0 self.a = 0 try: self.img = cv.load_image(os.path.join("assets", self.name.replace("*", "") + ".png"), int(bar_height), int(bar_height), self.chart.root, name) except: print("No image for {}".format(self.name)) self.img = None if isinstance(colors, dict): if name in colors: self.color = cv._from_rgb(colors[name]) else: self._set_color() else: self._set_color() self.draw(value) ``` -------------------------------- ### Initialize Country Object Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/WorldMap.html Sets up a country object with its name, canvas, coordinates, initial value, unit, font color, and color range. ```python def __init__(self, name=None, canvas=None, coords=[], value=0, unit=None, font_color=(0,0,0), colors=None, min_value=0): self.name = name self.canvas = canvas self.unite = unit self.font_color = font_color self.coords = coords # self.begin_color = (125, 100, 125) # dark self.begin_color = (255, 255, 255) # light self.current_color = self.begin_color self.colors = colors self.min_value = min_value self.polygons = [] self.draw() ``` -------------------------------- ### Create Animation Canvas with Canvas.canvas() Source: https://context7.com/sjoerdtilmans/sjvisualizer/llms.txt Initializes the main animation canvas, managing the window, subplots, and animation loop. Supports custom background colors, inclusion of a logo, and integration with other visualization components. ```python from sjvisualizer import Canvas, DataHandler # Create a full-screen canvas with custom background canvas = Canvas.canvas( bg=(255, 255, 255), # White background (RGB) include_logo=True # Include sjvisualizer watermark ) # Add title and subtitle canvas.add_title(text="My Data Visualization", color=(0, 0, 0)) canvas.add_sub_title(text="Time-series animation demo", color=(100, 100, 100)) # Load and prep data df = DataHandler.DataHandler( excel_file="data/example.xlsx", number_of_frames=60 * 60 * 0.5 # 30 seconds at 60fps ).df # Add time indicator canvas.add_time(df=df, time_indicator="year", color=(150, 150, 150)) # Add custom logo canvas.add_logo(logo="assets/my_logo.png") # Play the animation canvas.play( fps=60, record=True, file_name="output.mp4", width=1920, height=1080 ) ``` -------------------------------- ### Draw method for DynamicMatrix Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/DynamicMatrix.html The draw method is executed once at the start of the animation to set up graph elements and initial parameters like spacing and font size based on the data. ```python def draw(self, time): """This function gets executed only once at the start of the animation""" # get the data for the given time step data = self._get_data_for_frame(time) # create a dictionary to hold all graph_element objects self.graph_elements = {} self.spacing = self.height / len(data) / 2 if not hasattr(self, "neutral_string"): self.neutral_string = "0" if not hasattr(self, "font_size"): self.font_size = self.spacing if not hasattr(self, "level_count"): self.level_count = 2 if not hasattr(self, "color_range"): self.color_range = None y = self.y_pos + self.spacing # keep track of label widths self.max_label_width = 0 ``` -------------------------------- ### Load and Resize Image Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/Canvas.html Loads an image from a given path, resizes it, and converts it to a PhotoImage object. It ensures unique attribute names for the loaded image on the root object. ```python def load_image(path, x, y, root, name): load = Image.open(path) load = load.resize((int(x * load.size[0]/load.size[1]), int(y)), resample=2) load = ImageTk.PhotoImage(load) i = 0 while hasattr(root, name + str(i)): i = i + 1 setattr(root, name + str(i), load) return load ``` -------------------------------- ### BarRace Class Initialization Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/sjvisualizer.html Initializes the BarRace class with various parameters to configure the visualization. ```APIDOC ## BarRace Class ### Description Class to construct a bar race visualization. ### Parameters * **canvas** (tkinter.Canvas) – tkinter canvas to draw the graph to * **width** (int) – width of the plot in pixels, default depends on screen resolution * **height** (int) – height of the plot in pixels, default depends on screen resolution * **x_pos** (int) – the x location of the top left pixel in this plot, default depends on screen resolution * **y_pos** (int) – the y location of the top left pixel in this plot, default depends on screen resolution * **df** (pandas.DataFrame) – pandas dataframe that holds the data * **colors** (dict) – dictionary that holds color information for each of the data categories. The key of the dict should correspond to the name of the data category (column). The value of the dict should be the RGB values of the color. Example: `{"United States": [23, 60, 225]}`. Default is `{}`. * **unit** (str) – unit of the values visualized, default is "" * **back_ground_color** (tuple of length 3 with integers) – color of the background. To hide bars that fall outside of the top X, a square is drawn at the bottom of the visualization. Typically you want this square to match the color of the background. Default is (255,255,255). * **font_color** (tuple of length 3 with integers) – font color, default is (0,0,0) * **font_size** (int) – font size, in pixels * **text_font** (str) – selected font, defaults to 'Microsoft JhengHei UI' * **number_of_bars** (int) – number of bars to be displayed in the chart ``` -------------------------------- ### Get Element Positions Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/Legend.html Calculates and returns a list of y-positions for legend elements based on the legend's orientation. Currently, only 'vertical' orientation is supported; other orientations raise an error. ```python def _get_positions(self): if self.orientation == "vertical": self.positions = [self.y_pos + (i + 0.5) * self.height / (self.n) for i in range(self.n)] else: raise "{} orientation is not supported".format(self.orientation) ``` -------------------------------- ### DynamicMatrix Class Initialization Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/index.html Initializes the DynamicMatrix class with various parameters for data visualization. Supports customization of canvas, dimensions, dataframes, colors, and display options. ```python class sjvisualizer.DynamicMatrix.dynamic_matrix(_canvas=None_, _width=None_, _height=None_, _x_pos=None_, _y_pos=None_, _start_time=None_, _text=None_, _df=None_, _multi_color_df=None_, _anchor='c'_, _sort=True_, _colors={}, _root=None_, _display_percentages=True_, _display_label=True_, _title=None_, _invert=False_, _origin='s'_, _display_value=True_, _font_color=(0, 0, 0)_, _back_ground_color=(255, 255, 255)_, _events={}, _time_indicator='year'_, _number_of_bars=None_, _unit=''_, _x_ticks=4_, _y_ticks=4_, _log_scale=False_, _only_show_latest_event=True_, _allow_decrease=True_, _format='Europe'_, _draw_points=True_, _area=True_, _font_size=25_, _color_bar_color=[[100, 100, 100], [255, 0, 0]]_, _text_font='Microsoft JhengHei UI'_, _**kwargs_) ``` -------------------------------- ### Initialize Event Object Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/LineChart.html Initializes an event object with name, dates, colors, and font properties. Parses start and end dates and sets up the font for display. Automatically calls the draw method. ```python def __init__(self, name=None, canvas=None, start_date=None, end_date=None, font_color=(0,0,0), font_size=12, text_font="Microsoft JhengHei UI", parent=None, event_color=(255, 255, 255)): self.name = name self.canvas = canvas self.start_date = datetime.datetime.strptime(start_date, "%d/%m/%Y") self.end_date = datetime.datetime.strptime(end_date, "%d/%m/%Y") self.color = cv._from_rgb(event_color) self.font_color = font_color self.font_size = font_size self.text_font = text_font self.font = font.Font(family=self.text_font, size=int(self.font_size)) self.parent = parent self.drawn = False self.draw_label = False self.draw() ``` -------------------------------- ### Initialize DynamicMatrix Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/DynamicMatrix.html Initializes the DynamicMatrix class with various parameters for canvas, dimensions, data, and styling. Default values are used if parameters are not provided. ```python class dynamic_matrix(cv.sub_plot): """Example class to create custom data animations this class is derived from the sub_plot class :param canvas: tkinter canvas to draw the graph to :type canvas: tkinter.Canvas :param width: width of the plot in pixels, default depends on screen resolution :type width: int :param height: height of the plot in pixels, default depends on screen resolution :type height: int :param x_pos: the x location of the top left pixel in this plot, default depends on screen resolution :type x_pos: int :param y_pos: the y location of the top left pixel in this plot, default depends on screen resolution :type y_pos: int :param df: pandas dataframe that holds the data :type df: pandas.DataFrame :param colors: dictionary that holds color information for each of the data categories. The key of the dict should corespond to the name of the data category (column). The value of the dict should be the RGB values of the color: { "United States": [ 23, 60, 225 ] }, default is {} :type colors: dict :param font_color: font color, default is (0,0,0) :type font_color: tuple of length 3 with integers :param font_size: font size, in pixels :type font_size: int :param text_font: selected font, defaults to Microsoft JhengHei UI :type text_font: str :param level_count: defines the number of discrete sentiment levels displayed in the chart. If set to 3 the chart will display --- to +++, defaults to 2 :type level_count: int :param neutral_string: string to indicate a neutral value, by default set to 0 :type neutral_string: str :param color_range: list of 2 lists indicating the rgb values for fully negative to fully positive, defaults to [(255, 40, 60), (3, 175, 81)] :type color_range: list(list) """ ``` -------------------------------- ### Sub-plot Initialization Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/Canvas.html The base sub_plot class constructor initializes various parameters for a plot, including canvas, dimensions, positioning, and styling. It handles default values for width, height, and start time if not explicitly provided. ```python def __init__(self, canvas=None, width=None, height=None, x_pos=None, y_pos=None, start_time=None, text=None, df=None, multi_color_df=None, anchor="c", sort=True, colors={}, root=None, display_percentages=True, display_label=True, title=None, invert=False, origin="s", display_value=True, font_color=(0,0,0), back_ground_color=(255,255,255), events={}, time_indicator="year", number_of_bars=None, unit="", x_ticks = 4, y_ticks = 4, log_scale=False, only_show_latest_event=True, allow_decrease=True, format="Europe", draw_points=True, area=True, font_size=25, color_bar_color=[[100, 100, 100], [255, 0, 0]], text_font="Microsoft JhengHei UI", **kwargs): """ """ self.__dict__.update(kwargs) if width == None: self.width = 0.65 * WIDTH else: self.width = width if not isinstance(df, pd.DataFrame): if hasattr(self, "df_x"): df = self.df_x elif hasattr(self, "df_y"): df = self.df_y if height == None: self.height = 0.65 * HEIGHT self.height_is_set = False else: self.height_is_set = True self.height = height if not start_time and isinstance(df, pd.DataFrame): self.start_time = list(df.index)[0] else: self.start_time = start_time if not number_of_bars and isinstance(df, pd.DataFrame): if len(df.columns) < 10: self.number_of_bars = len(df.columns) else: self.number_of_bars = 10 else: self.number_of_bars = number_of_bars self.time_indicator = time_indicator if not hasattr(self, "decimal_places"): ``` -------------------------------- ### PieRace.draw Method Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/PieRace.html The draw method renders the pie chart slices, labels, and percentages based on the provided start and extent values. It handles different display conditions for labels and percentages depending on the slice size. ```APIDOC ## PieRace.draw Method ### Description This method draws the pie chart arcs, labels, and percentage indicators on the canvas. It dynamically adjusts font sizes and display conditions based on the `extent` of the slice and configuration options like `display_label` and `display_percentages`. ### Method `draw(self, start=0, extent=0)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming pie_race_instance is an instance of PieRace pie_race_instance.draw(start=0, extent=90) ``` ### Response #### Success Response (200) This method does not return a value. It modifies the canvas object by creating graphical elements. #### Response Example None ``` -------------------------------- ### Initialize StaticImage Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/StaticImage.html Use this class to add static images to your visualization. Specify the canvas, image dimensions, position, file path, and layering preference. ```python class static_image(sub_plot): """ Use this to add static images to your visualization. :param canvas: tkinter canvas to draw the graph to :type canvas: tkinter.Canvas :param width: width of the image in pixels :type width: int :param height: height of the image in pixels :type height: int :param x_pos: the x location of the top left pixel of this image :type x_pos: int :param y_pos: the y location of the top left pixel of this image :type y_pos: int :param file: file location of the image you want to add the canvas, only png files are support :type file: str :param on_top: set this to True to always draw this image on top :type on_top: boolean """ ``` -------------------------------- ### Draw BarRace Animation Frame Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/BarRace.html This function is executed once at the start of the animation to draw the initial state of the bar race chart. It retrieves data for the current frame, calculates bar heights, and creates bar objects for each data category. ```python def draw(self, time): """This function gets executed only once at the start of the animation""" # draw boudning box # self.canvas.create_rectangle(self.x_pos, self.y_pos, self.x_pos + self.width, self.y_pos + self.height) # get the data for the given time step data = self._get_data_for_frame(time) # create a dictionary to hold all graph_element objects self.graph_elements = {} # calculate desired bar_height bar_height = int(self.height / self.number_of_bars * 0.75) # loop over all values in the row for i, (name, d) in enumerate(data.items()): self.graph_elements[name] = bar(name=name, canvas=self.canvas, value=d, unit=self.unit, font_color=self.font_color, colors=self.colors, chart=self, text_font=self.text_font, font_size=self.font_size, bar_height=bar_height) # create axis data = self._get_data_for_frame(time) ``` -------------------------------- ### Initialize Pie Slice Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/PieRace.html Initializes a single pie slice with its properties, including position, color, and display options. Loads images if enabled and sets up animation parameters. ```python def __init__(self, name=None, canvas=None, x1=0, y1=0, x2=0, y2=0, start=0, extent=0, color=None, root=None, display_percentages=True, display_label=True, colors = None, load_img=True, font_color=(0, 0, 0), scale_label=True): self.name = name self.canvas = canvas self.target_start = start self.target_extend = extent self.load_img = load_img self.colors = colors size = y2 - y1 self.size = size self.display_label = display_label self.display_percentages = display_percentages self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 self.scale_label = scale_label self.start = start self.extent = extent self.v1 = 0 self.v2 = 0 self.a1 = 0 self.a2 = 0 self.stiffness = 0.06 self.damping = 0.35 self.mass = 1 self.font_color = font_color if self.load_img: try: self.imgs = {} print("Loading images for {}".format(self.name)) for i in range(int(self.size/7.5/min_slice_image*min_slice), int(self.size/7.5) + 1): self.imgs[i] = load_image(os.path.join("assets", self.name.replace("*", "") + ".png"), i, i, root, name) except: self.imgs = None else: self.imgs = None if color: self.color1 = _from_rgb(tuple(color)) self.color2 = _from_rgb(tuple((color[0] - 20, color[1] - 20, color[2] - 50))) else: color = tuple((random.randint(min_color, max_color), random.randint(min_color, max_color), random.randint(min_color + 30, max_color))) self.color1 = _from_rgb(color) self.color2 = _from_rgb(tuple((color[0] - 20, color[1] - 20, color[2] - 50))) ``` -------------------------------- ### graph_element Class Initialization (DynamicMatrix) Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/index.html Initializes a graph_element within the context of DynamicMatrix. ```APIDOC ## graph_element Constructor (DynamicMatrix) ### Description Initializes a graph_element, a component used within DynamicMatrix. ### Parameters - **name** (str) - The name of the graph element. - **y** (int) - The y-coordinate. - **canvas** (tkinter.Canvas) - The Tkinter canvas widget. - **value** (any) - The value associated with the element. - **unit** (str) - The unit of the value. - **font_color** (tuple) - RGB tuple for font color, default is (0, 0, 0). - **colors** (dict) - Dictionary for color mapping. - **font_size** (int) - Font size in pixels, default is 12. - **chart** (any) - The chart object this element belongs to. - **text_font** (str) - Font family for text, defaults to 'Microsoft JhengHei UI'. ``` -------------------------------- ### PieRace Methods Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/modules.html Methods for interacting with PieRace components. ```APIDOC ## PieRace Methods ### Description Provides methods for drawing and updating pie race visualizations. ### Methods - `pie.draw()` - `pie.update()` - `pie_plot.draw()` - `pie_plot.update()` ``` -------------------------------- ### Update Pie Slice Animation Source: https://github.com/sjoerdtilmans/sjvisualizer/blob/main/docs/_build/html/_modules/sjvisualizer/PieRace.html Animates the update of a pie slice's start and extent values. It calculates forces, accelerations, and velocities to smoothly transition the slice to its target state. Updates canvas items for the slice and its associated label and percentage text. ```python def update(self, target_start=0, target_extent=0): # if pie already exists and it should be updated if target_extent and self.obj_ID1: F1 = self.stiffness * (target_start - self.start) - self.damping * self.v1 F2 = self.stiffness * (target_extent - self.extent) - self.damping * self.v2 self.a1 = F1 / self.mass self.a2 = F2 / self.mass self.v1 = self.v1 + self.a1 self.v2 = self.v2 + self.a2 self.start = self.start + self.v1 self.extent = self.extent + self.v2 if self.extent > 0.5: self.canvas.itemconfig(self.obj_ID1, start=self.start, extent=self.extent) self.canvas.itemconfig(self.obj_ID2, start=self.start, extent=self.extent) x_dir = math.sin((90 - (self.extent + 2 * self.start) / 2) / 360 * 2 * math.pi) y_dir = math.cos((90 - (self.extent + 2 * self.start) / 2) / 360 * 2 * math.pi) if self.display_label: if self.extent > min_slice * 360: self.canvas.coords(self.line, (self.x1 + self.x2) / 2 + (self.size/2 + self.size/120) * x_dir, (self.y1 + self.y2) / 2 - (self.size/2 + self.size/120) * y_dir, (self.x1 + self.x2) / 2 + (self.size/2 + self.size/30) * x_dir, (self.y1 + self.y2) / 2 - (self.size/2 + self.size/30) * y_dir) self.canvas.itemconfig(self.text, text=self.name) if not self.extent > min_slice_percentage_display * 360 and self.scale_label: self.font_temp = font.Font(family=text_font, size=int( (12 + self.size / 150) / SCALEFACTOR * self.extent / ((0.5 * min_slice_percentage_display * 360 + 0.5 * self.extent))), weight="bold") self.canvas.itemconfig(self.text, font=self.font_temp) self.canvas.coords(self.text, ((self.x1 + self.x2) / 2 + (self.size/2 + self.size/12 + len(self.name) * (15 + self.size/30) * self.size/7500 + (15 + self.size/50)) * x_dir, (self.y1 + self.y2) / 2 - (self.size/2 + self.size/12) * y_dir)) if self.display_percentages: if self.extent > min_slice_percentage_display * 360: self.canvas.itemconfig(self.text2, text=format(self.extent/360*100, ",.{}f".format(decimal_places)) + "%") self.canvas.coords(self.text2, ((self.x1 + self.x2) / 2 + ( self.size / 2 + self.size / 12 + len(self.name) * (15 + self.size / 30) * self.size / 7500 + ( 15 + self.size / 50)) * x_dir, int((self.y1 + self.y2) / 2 - (self.size / 2 + self.size / 12) * y_dir) + self.size/30 + 10)) else: self.canvas.itemconfig(self.text2, text="") else: self.canvas.itemconfig(self.text, text="") self.canvas.coords(self.line, 0, 0, 0, 0) if self.display_percentages: self.canvas.itemconfig(self.text2, text="") ```