Icon

kn_​example_​python_​graphic_​time_​series_​grouped

Python graphics interactive - Time Series Grouped Interval

Python graphics interactive - Time Series Grouped Interval
https://hub.knime.com/-/spaces/-/latest/~vinUv_aveoS8qqv5/
https://forum.knime.com/t/conversion-of-multiple-rows-into-duration-bar-diagram/72023/7?u=mlauber71

Python graphics interactive - Time Series Grouped Intervalhttps://hub.knime.com/-/spaces/-/latest/~vinUv_aveoS8qqv5/https://forum.knime.com/t/conversion-of-multiple-rows-into-duration-bar-diagram/72023/7?u=mlauber71 import knime.scripting.io as knio# Import Librariesfrom io import BytesIOimport pandas as pdimport matplotlib.pyplot as plt# Retrieve input data and variablesinput_table = knio.input_tables[0].to_pandas()var_title = knio.flow_variables['title_graphic']var_footnote = knio.flow_variables['footnote_graphic']var_worker = knio.flow_variables['worker-selection']interval_minutes = knio.flow_variables['minute-input']# Filter dataset for the specified workerworker_data = input_table[input_table['Worker'] == var_worker].copy()worker_data['DateTime'] = pd.to_datetime(worker_data['DateTime'])# Create a figure with two subplots (axes)# fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(16, 9))fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(16, 10))# Group by the specified interval and calculate percentage distribution for each postureinterval = f"{interval_minutes}T" # Convert interval to Pandas offset alias formatgrouped_data = worker_data.groupby([pd.Grouper(key='DateTime', freq=interval), 'Posture']).size().unstack().fillna(0)grouped_percentage = grouped_data.divide(grouped_data.sum(axis=1), axis=0) * 100 # Order the columns for consistent color mappingordered_cols = ['good posture', 'neutral posture', 'bad posture']grouped_percentage = grouped_percentage[ordered_cols]# Plotting# Stacked Bar Chartgrouped_percentage.plot(kind='bar', stacked=True, ax=ax1, color=['green', 'yellow', 'red'])ax1.set_title(f"Percentage Distribution of Postures for {var_worker} over {interval_minutes}-minute Intervals")ax1.set_ylabel("Percentage (%)")ax1.set_xticks([]) # Hide x-ticks for the top plot# Filled Area Chart (Time Series)grouped_percentage.plot.area(ax=ax2, color=['green', 'yellow', 'red'], alpha=0.5)ax2.set_title(f"Percentage Distribution of Postures for {var_worker} over Time.")ax2.set_ylabel("Percentage (%)")# Adjusting the x-axis labelstotal_ticks = len(grouped_percentage)tick_frequency = total_ticks // 10time_labels = [str(x) for x in grouped_percentage.index[::tick_frequency]]ax2.set_xticks(grouped_percentage.index[::tick_frequency])ax2.set_xticklabels(time_labels, rotation=45, ha='right', fontsize=7)# Adding footnote and title# ax2.annotate(var_footnote, (0,0), (0, -70), xycoords='axes fraction', textcoords='offset points', va='top', size=8)# ax2.annotate(var_footnote, (0, 0), (10, -70), xycoords='axes fraction', textcoords='offset points', va='top', size=8, ha='left')# xy=(1, 0) positions the base of the text at the right edge of the subplot.# xytext=(5, 10) slightly offsets the text from the right edge and raises it a bit from the bottom.# rotation=90 rotates the text 90 degrees.# ha='center' and va='bottom' adjust the alignment of the rotated text.ax2.annotate(var_footnote, xy=(1.025, 0), xycoords='axes fraction', xytext=(6, 12), textcoords='offset points', ha='center', va='bottom', rotation=90, size=8)fig.suptitle(var_title, fontsize=18, ha='center')# Save the figure to a bufferbuffer = BytesIO()fig.savefig(buffer, format='svg')output_image = buffer.getvalue()# Set the output image for the KNIME nodeknio.output_images[0] = output_image# Assign the figure to the output_view variableknio.output_view = knio.view(fig) Medium: Create an Interactive Dashboard with KNIME Components and Pythonhttps://medium.com/p/41ef794b1467Medium: Exploring the Power of Python Graphics with KNIME: A Collection of Exampleshttps://medium.com/p/841df87b5563All Python-based Visualization Libraries Easily Accessible through KNIMEhttps://www.knime.com/blog/access-to-python-visualization-libraries df_worker_posture.parquetcreate theimage with matplotlibfrom_knime_<..>.png1.920 x 1.080PNG fileIneractive VIEWwith Python graphics(right click "Interactive View")"png_path"extract the name of thePNG selected in the componenttitle_graphicminute-inputfootnote_graphicloop by workerSTART1.920 x 1.080PNG fileimage_<..>.png"png_path"extract the name of thePNG selected in the componentv_graphic_nameloop by workerEND Parquet Reader Python Script Image Writer (Port) Renderer to Image Table To Image Image To Table Python graphics interactive -Time Series Grouped Interval Create File/FolderVariables Domain Calculator StringConfiguration IntegerConfiguration StringConfiguration Merge Variables Group Loop Start Image To Table Table To Image Renderer to Image Image Writer (Port) Create File/FolderVariables Java EditVariable (simple) Variable Loop End Python graphics interactive - Time Series Grouped Intervalhttps://hub.knime.com/-/spaces/-/latest/~vinUv_aveoS8qqv5/https://forum.knime.com/t/conversion-of-multiple-rows-into-duration-bar-diagram/72023/7?u=mlauber71 import knime.scripting.io as knio# Import Librariesfrom io import BytesIOimport pandas as pdimport matplotlib.pyplot as plt# Retrieve input data and variablesinput_table = knio.input_tables[0].to_pandas()var_title = knio.flow_variables['title_graphic']var_footnote = knio.flow_variables['footnote_graphic']var_worker = knio.flow_variables['worker-selection']interval_minutes = knio.flow_variables['minute-input']# Filter dataset for the specified workerworker_data = input_table[input_table['Worker'] == var_worker].copy()worker_data['DateTime'] = pd.to_datetime(worker_data['DateTime'])# Create a figure with two subplots (axes)# fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(16, 9))fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(16, 10))# Group by the specified interval and calculate percentage distribution for each postureinterval = f"{interval_minutes}T" # Convert interval to Pandas offset alias formatgrouped_data = worker_data.groupby([pd.Grouper(key='DateTime', freq=interval), 'Posture']).size().unstack().fillna(0)grouped_percentage = grouped_data.divide(grouped_data.sum(axis=1), axis=0) * 100 # Order the columns for consistent color mappingordered_cols = ['good posture', 'neutral posture', 'bad posture']grouped_percentage = grouped_percentage[ordered_cols]# Plotting# Stacked Bar Chartgrouped_percentage.plot(kind='bar', stacked=True, ax=ax1, color=['green', 'yellow', 'red'])ax1.set_title(f"Percentage Distribution of Postures for {var_worker} over {interval_minutes}-minute Intervals")ax1.set_ylabel("Percentage (%)")ax1.set_xticks([]) # Hide x-ticks for the top plot# Filled Area Chart (Time Series)grouped_percentage.plot.area(ax=ax2, color=['green', 'yellow', 'red'], alpha=0.5)ax2.set_title(f"Percentage Distribution of Postures for {var_worker} over Time.")ax2.set_ylabel("Percentage (%)")# Adjusting the x-axis labelstotal_ticks = len(grouped_percentage)tick_frequency = total_ticks // 10time_labels = [str(x) for x in grouped_percentage.index[::tick_frequency]]ax2.set_xticks(grouped_percentage.index[::tick_frequency])ax2.set_xticklabels(time_labels, rotation=45, ha='right', fontsize=7)# Adding footnote and title# ax2.annotate(var_footnote, (0,0), (0, -70), xycoords='axes fraction', textcoords='offset points', va='top', size=8)# ax2.annotate(var_footnote, (0, 0), (10, -70), xycoords='axes fraction', textcoords='offset points', va='top', size=8, ha='left')# xy=(1, 0) positions the base of the text at the right edge of the subplot.# xytext=(5, 10) slightly offsets the text from the right edge and raises it a bit from the bottom.# rotation=90 rotates the text 90 degrees.# ha='center' and va='bottom' adjust the alignment of the rotated text.ax2.annotate(var_footnote, xy=(1.025, 0), xycoords='axes fraction', xytext=(6, 12), textcoords='offset points', ha='center', va='bottom', rotation=90, size=8)fig.suptitle(var_title, fontsize=18, ha='center')# Save the figure to a bufferbuffer = BytesIO()fig.savefig(buffer, format='svg')output_image = buffer.getvalue()# Set the output image for the KNIME nodeknio.output_images[0] = output_image# Assign the figure to the output_view variableknio.output_view = knio.view(fig) Medium: Create an Interactive Dashboard with KNIME Components and Pythonhttps://medium.com/p/41ef794b1467Medium: Exploring the Power of Python Graphics with KNIME: A Collection of Exampleshttps://medium.com/p/841df87b5563All Python-based Visualization Libraries Easily Accessible through KNIMEhttps://www.knime.com/blog/access-to-python-visualization-libraries df_worker_posture.parquetcreate theimage with matplotlibfrom_knime_<..>.png1.920 x 1.080PNG fileIneractive VIEWwith Python graphics(right click "Interactive View")"png_path"extract the name of thePNG selected in the componenttitle_graphicminute-inputfootnote_graphicloop by workerSTART1.920 x 1.080PNG fileimage_<..>.png"png_path"extract the name of thePNG selected in the componentv_graphic_nameloop by workerEND Parquet Reader Python Script Image Writer (Port) Renderer to Image Table To Image Image To Table Python graphics interactive -Time Series Grouped Interval Create File/FolderVariables Domain Calculator StringConfiguration IntegerConfiguration StringConfiguration Merge Variables Group Loop Start Image To Table Table To Image Renderer to Image Image Writer (Port) Create File/FolderVariables Java EditVariable (simple) Variable Loop End

Nodes

Extensions

Links