Icon

kn_​example_​python_​graphic_​bar_​chart_​percentage_​change

Python graphics: Annual Comparative Analysis: Visualizing Year-over-Year Value Changes

Summary:
This script is designed to perform a comparative analysis of yearly data, visualizing the changes in various values across consecutive years. It starts by importing data from a KNIME workflow, focusing on a set of values recorded over multiple years. The script calculates the percentage change for each value from one year to the next, providing a clear year-over-year comparison.

The core of the script lies in its ability to visually represent these changes through a bar chart, where each year is represented on the X-axis and is accompanied by a group of bars. Each bar in a group corresponds to a specific value, illustrating how it has evolved from the previous year. The bars are annotated with the actual numerical value and the calculated percentage change, offering an immediate and clear understanding of the data's trajectory.

This visualization is particularly useful for identifying trends, patterns, and anomalies in the dataset, making it an invaluable tool for data analysis, financial review, or performance tracking. The final output is a comprehensive and interactive plot, which is then integrated back into the KNIME workflow for further use or presentation purposes.

Python graphics: Annual Comparative Analysis: Visualizing Year-over-Year Value Changeshttps://forum.knime.com/t/barchart-with-labels/75558/2?u=mlauber71 Summary:This script is designed to perform a comparative analysis of yearly data, visualizing the changes invarious values across consecutive years. It starts by importing data from a KNIME workflow,focusing on a set of values recorded over multiple years. The script calculates the percentagechange for each value from one year to the next, providing a clear year-over-year comparison.The core of the script lies in its ability to visually represent these changes through a bar chart,where each year is represented on the X-axis and is accompanied by a group of bars. Each bar ina group corresponds to a specific value, illustrating how it has evolved from the previous year. Thebars are annotated with the actual numerical value and the calculated percentage change, offeringan immediate and clear understanding of the data's trajectory.This visualization is particularly useful for identifying trends, patterns, and anomalies in thedataset, making it an invaluable tool for data analysis, financial review, or performance tracking.The final output is a comprehensive and interactive plot, which is then integrated back into theKNIME workflow for further use or presentation purposes. import knime.scripting.io as knioimport numpy as npimport matplotlib.pyplot as pltfrom io import BytesIOimport pandas as pdimport pyarrow.parquet as pq# Load data from the first input table in KNIMEdf = knio.input_tables[0].to_pandas()# Calculate percentage change year-over-year and fill NaN values with 0# This is done for each value across the columns (years)df_pct_change = df.pct_change(axis='columns').fillna(0) * 100# export the file to Parquet - using GZIP# you could also try and use a different pathv_parquet_file = knio.flow_variables['v_path_parquet_file']# import the local parquet file into Python as 'df' dataframedf_pct_change.to_parquet(v_parquet_file, compression='gzip')# Begin plottingfig, ax = plt.subplots()num_values = len(df) # Number of different values (rows) in the datasetwidth = 0.8 / num_values # Calculate the width of each bar to fit all in one groupx = np.arange(len(df.columns)) # X-axis positions for each group of bars (one group per year)# Loop through each value to create a set of bars for eachfor i in range(num_values): values = df.iloc[i] # Get the values for the current row pct_changes = df_pct_change.iloc[i] # Get the percentage changes for the current row # Create a bar for each year for the current value bars = ax.bar(x - 0.4 + width*i, values, width, label=f'Value {i+1}') # Add annotations on each bar for bar, pct_change in zip(bars, pct_changes): height = bar.get_height() # Annotate each bar with its height (value) and the percentage change ax.annotate(f'{height:.0f}\n({pct_change:+.1f}%)', xy=(bar.get_x() + bar.get_width() / 2, height), xytext=(0, 3), # Offset the text by 3 points vertically textcoords="offset points", ha='center', va='bottom')# Set labels and title for the plotax.set_xlabel('Years')ax.set_ylabel('Amount')ax.set_title('Yearly Values with Percentage Change')# Set the positions and labels for the X-axis ticks (one for each year)ax.set_xticks(x)ax.set_xticklabels(df.columns)# Add a legend to the plotax.legend()# Adjust the size of the figurefig.set_size_inches(16, 9)# Create a buffer to store the image of the plotbuffer = BytesIO()# Save the plot to the buffer in SVG formatfig.savefig(buffer, format='svg')# Retrieve the content of the buffer (the image data)output_image = buffer.getvalue()# Assign the image to the first output image in KNIMEknio.output_images[0] = output_image# Assign the figure to the output view variable for display in KNIMEknio.output_view = knio.view(fig) Exploring the Power of Python Graphics with KNIME: A Collection of Exampleshttps://medium.com/p/841df87b5563Create an Interactive Dashboard with KNIME Components and Pythonhttps://medium.com/p/41ef794b1467 create initial dataexecute code20*ensure the correctsortingmake sureyears properlysortedv_path_parquet_filedf_pct_change.parquetv_path_*1.920 x 1.080PNG filefrom_knime_histogram_with_pct_changes.pnglocate and create/data/ folderwith absolute pathsdf_pct_change.parquet Python Script Python View Extract Table Spec Row Filter Sorter ReferenceColumn Resorter Column Filter Java EditVariable (simple) String to Path(Variable) Image To Table Renderer to Image Table To Image Image Writer (Port) Collect LocalMetadata Parquet Reader Python graphics: Annual Comparative Analysis: Visualizing Year-over-Year Value Changeshttps://forum.knime.com/t/barchart-with-labels/75558/2?u=mlauber71 Summary:This script is designed to perform a comparative analysis of yearly data, visualizing the changes invarious values across consecutive years. It starts by importing data from a KNIME workflow,focusing on a set of values recorded over multiple years. The script calculates the percentagechange for each value from one year to the next, providing a clear year-over-year comparison.The core of the script lies in its ability to visually represent these changes through a bar chart,where each year is represented on the X-axis and is accompanied by a group of bars. Each bar ina group corresponds to a specific value, illustrating how it has evolved from the previous year. Thebars are annotated with the actual numerical value and the calculated percentage change, offeringan immediate and clear understanding of the data's trajectory.This visualization is particularly useful for identifying trends, patterns, and anomalies in thedataset, making it an invaluable tool for data analysis, financial review, or performance tracking.The final output is a comprehensive and interactive plot, which is then integrated back into theKNIME workflow for further use or presentation purposes. import knime.scripting.io as knioimport numpy as npimport matplotlib.pyplot as pltfrom io import BytesIOimport pandas as pdimport pyarrow.parquet as pq# Load data from the first input table in KNIMEdf = knio.input_tables[0].to_pandas()# Calculate percentage change year-over-year and fill NaN values with 0# This is done for each value across the columns (years)df_pct_change = df.pct_change(axis='columns').fillna(0) * 100# export the file to Parquet - using GZIP# you could also try and use a different pathv_parquet_file = knio.flow_variables['v_path_parquet_file']# import the local parquet file into Python as 'df' dataframedf_pct_change.to_parquet(v_parquet_file, compression='gzip')# Begin plottingfig, ax = plt.subplots()num_values = len(df) # Number of different values (rows) in the datasetwidth = 0.8 / num_values # Calculate the width of each bar to fit all in one groupx = np.arange(len(df.columns)) # X-axis positions for each group of bars (one group per year)# Loop through each value to create a set of bars for eachfor i in range(num_values): values = df.iloc[i] # Get the values for the current row pct_changes = df_pct_change.iloc[i] # Get the percentage changes for the current row # Create a bar for each year for the current value bars = ax.bar(x - 0.4 + width*i, values, width, label=f'Value {i+1}') # Add annotations on each bar for bar, pct_change in zip(bars, pct_changes): height = bar.get_height() # Annotate each bar with its height (value) and the percentage change ax.annotate(f'{height:.0f}\n({pct_change:+.1f}%)', xy=(bar.get_x() + bar.get_width() / 2, height), xytext=(0, 3), # Offset the text by 3 points vertically textcoords="offset points", ha='center', va='bottom')# Set labels and title for the plotax.set_xlabel('Years')ax.set_ylabel('Amount')ax.set_title('Yearly Values with Percentage Change')# Set the positions and labels for the X-axis ticks (one for each year)ax.set_xticks(x)ax.set_xticklabels(df.columns)# Add a legend to the plotax.legend()# Adjust the size of the figurefig.set_size_inches(16, 9)# Create a buffer to store the image of the plotbuffer = BytesIO()# Save the plot to the buffer in SVG formatfig.savefig(buffer, format='svg')# Retrieve the content of the buffer (the image data)output_image = buffer.getvalue()# Assign the image to the first output image in KNIMEknio.output_images[0] = output_image# Assign the figure to the output view variable for display in KNIMEknio.output_view = knio.view(fig) Exploring the Power of Python Graphics with KNIME: A Collection of Exampleshttps://medium.com/p/841df87b5563Create an Interactive Dashboard with KNIME Components and Pythonhttps://medium.com/p/41ef794b1467 create initial dataexecute code20*ensure the correctsortingmake sureyears properlysortedv_path_parquet_filedf_pct_change.parquetv_path_*1.920 x 1.080PNG filefrom_knime_histogram_with_pct_changes.pnglocate and create/data/ folderwith absolute pathsdf_pct_change.parquetPython Script Python View Extract Table Spec Row Filter Sorter ReferenceColumn Resorter Column Filter Java EditVariable (simple) String to Path(Variable) Image To Table Renderer to Image Table To Image Image Writer (Port) Collect LocalMetadata Parquet Reader

Nodes

Extensions

Links