Icon

kn_​example_​python_​graphic_​linechart_​date

KNIME & Python Graphics - Linechart with date variables on x axis

KNIME & Python Graphics - Linechart with date variables on x axis


Exploring the Power of Python Graphics with KNIME: A Collection of Examples
https://medium.com/p/841df87b5563








KNIME & Python Graphics - Linechart with date variables on x axishttps://forum.knime.com/t/scatter-plot-diagonal-reference-line/73484/2?u=mlauber71https://hub.knime.com/-/spaces/-/latest/~TQl4cycTtFLs4cnA/ # ----- IMPORTS -----import knime.scripting.io as knioimport pandas as pdimport numpy as npfrom io import BytesIOimport matplotlib.pyplot as pltfrom matplotlib.ticker import MaxNLocator, FuncFormatterfrom matplotlib.dates import (AutoDateLocator, AutoDateFormatter, DayLocator, MonthLocator, YearLocator, WeekdayLocator, DateFormatter, MO)# ----- DATA INPUT & VARIABLE INITIALIZATION -----input_table = knio.input_tables[0].to_pandas()# Extract flow variablesfont_size = knio.flow_variables['font_size']var_title = knio.flow_variables['title_graphic']var_footnote = knio.flow_variables['footnote_graphic']var_x_variable = knio.flow_variables['variable_x']var_x_label = knio.flow_variables['label_x']var_y_a_variable = knio.flow_variables['variable_y_a']var_y_a_label = knio.flow_variables['label_y_a']var_y_a_colour = knio.flow_variables['v_colour']var_marker = knio.flow_variables['v_marker']x_axis_format = knio.flow_variables['x_axis_format']vertical_grid_setting = knio.flow_variables['show_vertical_grid']horizontal_grid_setting = knio.flow_variables['show_horizontal_grid']# Convert grid settings to booleanshow_vertical_grid = bool(vertical_grid_setting)show_horizontal_grid = bool(horizontal_grid_setting)# ----- FUNCTION DEFINITIONS -----# Define a function to format the tick labels with thousands separatorsdef thousands_formatter(x, pos): return f'{x:,.0f}'# ----- PLOTTING -----# Create a figure and set of subplotsfig, ax1 = plt.subplots(figsize=(16, 9))# Plot the primary y-axis datadate_rng = input_table[var_x_variable]y1 = input_table[var_y_a_variable]var_ax1_color = var_y_a_colour + "-"ax1.plot(date_rng, y1, var_ax1_color, alpha=0.7, marker=var_marker)# Set axis labels and propertiesax1.set_xlabel(var_x_label, fontsize=font_size+5)ax1.set_ylabel(var_y_a_label, color=var_y_a_colour, fontsize=font_size+5)ax1.tick_params('y', colors=var_y_a_colour)ax1.yaxis.set_major_formatter(FuncFormatter(thousands_formatter))ax1.yaxis.set_major_locator(MaxNLocator(integer=True, prune='both', nbins=10))# Set x-axis date formattingif x_axis_format == 'auto': date_locator = AutoDateLocator() date_formatter = AutoDateFormatter(date_locator)elif x_axis_format == 'day': date_locator = DayLocator() date_formatter = DateFormatter('%d')elif x_axis_format == 'month': date_locator = MonthLocator() date_formatter = DateFormatter('%b %Y')elif x_axis_format == 'year': date_locator = YearLocator() date_formatter = DateFormatter('%Y')elif x_axis_format == 'week': date_locator = WeekdayLocator(byweekday=MO) date_formatter = DateFormatter('%b %d, %Y')ax1.xaxis.set_major_locator(date_locator)ax1.xaxis.set_major_formatter(date_formatter)# Set x-axis label rotationrotation_value = knio.flow_variables['x_axis_rotation']if rotation_value == 'vertical': angle = 90elif rotation_value == 'horizontal': angle = 0else: angle = int(rotation_value)plt.setp(ax1.get_xticklabels(), rotation=angle, ha="right", va="center")# Grid settingsif show_vertical_grid: ax1.xaxis.grid(True, linestyle='--', which='major', color='lightgrey', alpha=0.5)else: ax1.xaxis.grid(False)if show_horizontal_grid: ax1.yaxis.grid(True, linestyle='--', which='major', color='lightgrey', alpha=0.5)else: ax1.yaxis.grid(False)# Adjust font size to avoid overlapoverlapping = Truewhile overlapping and font_size > 5: plt.setp(ax1.get_xticklabels(), fontsize=font_size) plt.draw() bounding_boxes = [tick.get_window_extent() for tick in ax1.get_xticklabels()] overlapping = any(b1.overlaps(b2) for b1 in bounding_boxes for b2 in bounding_boxes if b1 != b2) font_size -= 1# Adjust distance between tick labels and axisax1.tick_params(axis='x', which='major', pad=15)# Annotations and titleax1.annotate(var_footnote, (0, 0), (0, -60), xycoords='axes fraction', textcoords='offset points', va='top', size=font_size-1)fig.suptitle(var_title, fontsize=font_size+8, ha='center')# ----- OUTPUT -----# Create buffer, save figure to it, and set outputbuffer = BytesIO()fig.savefig(buffer, format='svg')output_image = buffer.getvalue()knio.output_images[0] = output_imageknio.output_view = knio.view(fig) Exploring the Power of Python Graphics with KNIME: A Collection of Exampleshttps://medium.com/p/841df87b5563 Other sample data - "Daily Minimum Temperatures in Melbourne" from 1981 to 1990. locate and create/data/ folderwith absolute paths1.920 x 1.080PNG filefrom_knime_linechart_dates.pngdaily-min-temperatures.parquetIneractive VIEWwith Python graphics(right click)Chart - monthly PA vs Time.csvDatedaily-min-temperatures.csvDatejoin($MMofExec$,"01")AmbExpendChart - monthly PA vs Time.parquet Collect LocalMetadata Image To Table Renderer to Image Table To Image Image Writer (Port) Parquet Writer Python graphics interactive - Linechartwith date variables on x axis CSV Reader String to Date&Time CSV Reader String to Date&Time Number To String String Manipulation Column Rename Parquet Writer KNIME & Python Graphics - Linechart with date variables on x axishttps://forum.knime.com/t/scatter-plot-diagonal-reference-line/73484/2?u=mlauber71https://hub.knime.com/-/spaces/-/latest/~TQl4cycTtFLs4cnA/ # ----- IMPORTS -----import knime.scripting.io as knioimport pandas as pdimport numpy as npfrom io import BytesIOimport matplotlib.pyplot as pltfrom matplotlib.ticker import MaxNLocator, FuncFormatterfrom matplotlib.dates import (AutoDateLocator, AutoDateFormatter, DayLocator, MonthLocator, YearLocator, WeekdayLocator, DateFormatter, MO)# ----- DATA INPUT & VARIABLE INITIALIZATION -----input_table = knio.input_tables[0].to_pandas()# Extract flow variablesfont_size = knio.flow_variables['font_size']var_title = knio.flow_variables['title_graphic']var_footnote = knio.flow_variables['footnote_graphic']var_x_variable = knio.flow_variables['variable_x']var_x_label = knio.flow_variables['label_x']var_y_a_variable = knio.flow_variables['variable_y_a']var_y_a_label = knio.flow_variables['label_y_a']var_y_a_colour = knio.flow_variables['v_colour']var_marker = knio.flow_variables['v_marker']x_axis_format = knio.flow_variables['x_axis_format']vertical_grid_setting = knio.flow_variables['show_vertical_grid']horizontal_grid_setting = knio.flow_variables['show_horizontal_grid']# Convert grid settings to booleanshow_vertical_grid = bool(vertical_grid_setting)show_horizontal_grid = bool(horizontal_grid_setting)# ----- FUNCTION DEFINITIONS -----# Define a function to format the tick labels with thousands separatorsdef thousands_formatter(x, pos): return f'{x:,.0f}'# ----- PLOTTING -----# Create a figure and set of subplotsfig, ax1 = plt.subplots(figsize=(16, 9))# Plot the primary y-axis datadate_rng = input_table[var_x_variable]y1 = input_table[var_y_a_variable]var_ax1_color = var_y_a_colour + "-"ax1.plot(date_rng, y1, var_ax1_color, alpha=0.7, marker=var_marker)# Set axis labels and propertiesax1.set_xlabel(var_x_label, fontsize=font_size+5)ax1.set_ylabel(var_y_a_label, color=var_y_a_colour, fontsize=font_size+5)ax1.tick_params('y', colors=var_y_a_colour)ax1.yaxis.set_major_formatter(FuncFormatter(thousands_formatter))ax1.yaxis.set_major_locator(MaxNLocator(integer=True, prune='both', nbins=10))# Set x-axis date formattingif x_axis_format == 'auto': date_locator = AutoDateLocator() date_formatter = AutoDateFormatter(date_locator)elif x_axis_format == 'day': date_locator = DayLocator() date_formatter = DateFormatter('%d')elif x_axis_format == 'month': date_locator = MonthLocator() date_formatter = DateFormatter('%b %Y')elif x_axis_format == 'year': date_locator = YearLocator() date_formatter = DateFormatter('%Y')elif x_axis_format == 'week': date_locator = WeekdayLocator(byweekday=MO) date_formatter = DateFormatter('%b %d, %Y')ax1.xaxis.set_major_locator(date_locator)ax1.xaxis.set_major_formatter(date_formatter)# Set x-axis label rotationrotation_value = knio.flow_variables['x_axis_rotation']if rotation_value == 'vertical': angle = 90elif rotation_value == 'horizontal': angle = 0else: angle = int(rotation_value)plt.setp(ax1.get_xticklabels(), rotation=angle, ha="right", va="center")# Grid settingsif show_vertical_grid: ax1.xaxis.grid(True, linestyle='--', which='major', color='lightgrey', alpha=0.5)else: ax1.xaxis.grid(False)if show_horizontal_grid: ax1.yaxis.grid(True, linestyle='--', which='major', color='lightgrey', alpha=0.5)else: ax1.yaxis.grid(False)# Adjust font size to avoid overlapoverlapping = Truewhile overlapping and font_size > 5: plt.setp(ax1.get_xticklabels(), fontsize=font_size) plt.draw() bounding_boxes = [tick.get_window_extent() for tick in ax1.get_xticklabels()] overlapping = any(b1.overlaps(b2) for b1 in bounding_boxes for b2 in bounding_boxes if b1 != b2) font_size -= 1# Adjust distance between tick labels and axisax1.tick_params(axis='x', which='major', pad=15)# Annotations and titleax1.annotate(var_footnote, (0, 0), (0, -60), xycoords='axes fraction', textcoords='offset points', va='top', size=font_size-1)fig.suptitle(var_title, fontsize=font_size+8, ha='center')# ----- OUTPUT -----# Create buffer, save figure to it, and set outputbuffer = BytesIO()fig.savefig(buffer, format='svg')output_image = buffer.getvalue()knio.output_images[0] = output_imageknio.output_view = knio.view(fig) Exploring the Power of Python Graphics with KNIME: A Collection of Exampleshttps://medium.com/p/841df87b5563 Other sample data - "Daily Minimum Temperatures in Melbourne" from 1981 to 1990. locate and create/data/ folderwith absolute paths1.920 x 1.080PNG filefrom_knime_linechart_dates.pngdaily-min-temperatures.parquetIneractive VIEWwith Python graphics(right click)Chart - monthly PA vs Time.csvDatedaily-min-temperatures.csvDatejoin($MMofExec$,"01")AmbExpendChart - monthly PA vs Time.parquetCollect LocalMetadata Image To Table Renderer to Image Table To Image Image Writer (Port) Parquet Writer Python graphics interactive - Linechartwith date variables on x axis CSV Reader String to Date&Time CSV Reader String to Date&Time Number To String String Manipulation Column Rename Parquet Writer

Nodes

Extensions

Links