Fixed save plot image and points tag values

This commit is contained in:
georgemihaila
2020-10-12 14:04:48 -05:00
parent 95bd8c0c84
commit f48cc53eaa

View File

@@ -20,27 +20,89 @@ import warnings
from sklearn.metrics import confusion_matrix
def plot_array(array, step_size=1, use_label=None, use_title=None, use_xlabel=None, use_ylabel=None,
style_sheet='ggplot', use_grid=True, width=3, height=1, use_linestyle='-',
magnify=1.2, use_dpi=20, path=None, show_plot=True):
"""Create plot from a single array of values.
:param magnify:
:param array: list of values. Can be of type list or np.ndarray.
:param step_size: steps shows on x-axis. Change if each steps is different than 1.
:param use_label: display label of values from array.
:param use_title: title on top of plot.
:param use_xlabel: horizontal axis label.
:param use_ylabel: vertical axis label.
:param style_sheet: style of plot. Use plt.style.available to show all styles.
:param use_grid: show grid on plot or not.
:param width: horizontal length of plot.
:param height: vertical length of plot.
:param use_linestyle: what style to use on line from ['-', '--', '-.', ':'].
:param use_dpi: quality of image saved from plot. 100 is pretty high.
:param path: path where to save the plot as an image - if set to None no image will be saved.
:param show_plot: if you want to call `plt.show()`. or not (if you run on a headless server).
:return:
def plot_array(array, start_step=0, step_size=1, use_label=None, use_title=None, points_values=False, use_xlabel=None,
use_xticks=True, use_ylabel=None, style_sheet='ggplot', use_grid=True, use_linestyle='-', width=3,
height=1, magnify=1.2, use_dpi=50, path=None, show_plot=True):
r"""Create plot from a single array of values.
Arguments:
array (:obj:`list / np.ndarray`):
List of values. Can be of type list or np.ndarray.
start_step (:obj:`int`, `optional`, defaults to :obj:`0`):
Value to offset all x-axis values. This argument is optional and it has a default value attributed inside
the function.
step_size (:obj:`int`, `optional`, defaults to :obj:`1`):
This argument is optional and it has a default value attributed inside the function. It will multiply
each x-axis position value to it.
use_label (:obj:`str`, `optional`):
Display label on plot for whole array. This argument is optional and it will have a None value attributed
inside the function.
use_title (:obj:`str`, `optional`):
Title on top of plot. This argument is optional and it will have a None value attributed inside the
function for which it won't display any title.
points_values (:obj:`bool`, `optional`, defaults to :obj:`False`):
Display each point value on the plot. This argument is optional and it has a default value attributed
inside the function.
use_xlabel (:obj:`str`, `optional`):
Label to use for x-axis value meaning. This argument is optional and it will have a None value attributed
inside the function.
use_xticks (:obj:`bool`, `optional`, defaults to :obj:`True`):
Display x-axis tick values. This argument is optional and it has a default value attributed
inside the function.
use_ylabel (:obj:`str`, `optional`):
Label to use for y-axis value meaning. This argument is optional and it will have a None value attributed
inside the function.
style_sheet (:obj:`str`, `optional`, defaults to :obj:`ggplot`):
Style of plot. Use plt.style.available to show all styles. This argument is optional and it has a default
value attributed inside the function.
use_grid (:obj:`bool`, `optional`, defaults to :obj:`True`):
Show grid on plot or not. This argument is optional and it has a default value attributed inside
the function.
use_linestyle (:obj:`str`, `optional`, defaults to :obj:`-`):
Style to use on line from ['-', '--', '-.', ':']. This argument is optional and it has a default
value attributed inside the function.
width (:obj:`int`, `optional`, defaults to :obj:`3`):
Horizontal length of plot. This argument is optional and it has a default value attributed inside
the function.
height (:obj:`int`, `optional`, defaults to :obj:`1`):
Vertical length of plot. This argument is optional and it has a default value attributed inside
the function.
magnify (:obj:`int`, `optional`, defaults to :obj:`1.2`):
Vertical length of plot. This argument is optional and it has a default value attributed inside
the function.
use_dpi (:obj:`int`, `optional`, defaults to :obj:`50`):
Vertical length of plot. This argument is optional and it has a default value attributed inside
the function.
path (:obj:`str`, `optional`):
Vertical length of plot. This argument is optional and it will have a None value attributed inside
the function.
show_plot (:obj:`bool`, `optional`, defaults to :obj:`1`):
if you want to call `plt.show()`. or not (if you run on a headless server). This argument is optional and
it has a default value attributed inside the function.
Returns:
None
"""
# check if `array` is correct format
if not isinstance(array, list) or isinstance(array, np.ndarray):
# raise value error
@@ -62,15 +124,28 @@ def plot_array(array, step_size=1, use_label=None, use_title=None, use_xlabel=No
raise ValueError("`linestyle=%s` is not in the styles: %s!" % (str(use_linestyle), str(linestyles)))
# set steps plotted on x-axis - we can use step if 1 unit has different value
steps = np.array(range(1, len(array) + 1)) * step_size
if start_step > 0:
# Offset all steps by start_step.
steps = np.array(range(0, len(array))) * step_size + start_step
else:
steps = np.array(range(1, len(array) + 1)) * step_size
# single plot figure
plt.subplot(1, 2, 1)
# plot array as a single line
plt.plot(steps, array, linestyle=use_linestyle, label=use_label)
# Plots points values
if points_values:
# Loop through each point and plot the label.
for x, y in zip(steps, array):
# Add text label to plo.
plt.text(x, y, str(y))
# set title of figure
plt.title(use_title)
# set horizontal axis name
plt.xlabel(use_xlabel)
# Use x ticks with steps.
plt.xticks(steps) if use_xticks else None
# set vertical axis name
plt.ylabel(use_ylabel)
# place legend best position
@@ -88,19 +163,18 @@ def plot_array(array, step_size=1, use_label=None, use_title=None, use_xlabel=No
# set the new figure size
fig.set_size_inches(figsize)
# save figure to image if path is set
fig.savefig(path, dpi=use_dpi) if path is not None else None
fig.savefig(path, dpi=use_dpi, bbox_inches='tight') if path is not None else None
# show plot
plt.show() if show_plot is True else None
return
def plot_dict(dict_arrays, step_size=1, use_title=None, use_xlabel=None, use_ylabel=None,
style_sheet='ggplot', use_grid=True, width=3, height=1, use_linestyles=None, magnify=1.2,
use_dpi=20, path=None, show_plot=True):
def plot_dict(dict_arrays, step_size=1, use_title=None, points_values=False, use_xlabel=None, use_ylabel=None,
style_sheet='ggplot', use_grid=True, width=3, height=1, use_linestyles=None, magnify=1.2,
use_dpi=50, path=None, show_plot=True):
"""Create plot from a single array of values.
:param magnify:
:param dict_arrays:
:param array: dictionary of lists or np.array
:param step_size: steps shows on x-axis. Change if each steps is different than 1.
:param use_title: title on top of plot.
:param use_xlabel: horizontal axis label.
@@ -109,8 +183,8 @@ def plot_dict(dict_arrays, step_size=1, use_title=None, use_xlabel=None, use_yla
:param use_grid: show grid on plot or not.
:param width: horizontal length of plot.
:param height: vertical length of plot.
:param use_linestyles: what style to use on line from ['-', '--', '-.', ':'].
:param use_dpi: quality of image saved from plot. 100 is pretty high.
:param use_linestyle: whtat style to use on line from ['-', '--', '-.', ':'].
:param use_dpi: quality of image saved from plot. 100 is prety high.
:param path: path where to save the plot as an image - if set to None no image will be saved.
:param show_plot: if you want to call `plt.show()`. or not (if you run on a headless server).
:return:
@@ -118,7 +192,7 @@ def plot_dict(dict_arrays, step_size=1, use_title=None, use_xlabel=None, use_yla
# check if `dict_arrays` is correct format
if not isinstance(dict_arrays, dict):
# raise value error
raise ValueError("`array` needs to be a dictionary of values!")
raise ValueError("`array` needs to be a dicitonary of values!")
for label, array in dict_arrays.items():
# check if format is correct
if not isinstance(label, str):
@@ -139,22 +213,28 @@ def plot_dict(dict_arrays, step_size=1, use_title=None, use_xlabel=None, use_yla
linestyles = ['-', '--', '-.', ':']
if use_linestyles is None:
use_linestyles = ['-'] * len(dict_arrays)
use_linestyles = ['-']*len(dict_arrays)
else:
# check if linestyle is set right
for use_linestyle in use_linestyles:
if use_linestyle not in linestyles:
# raise error
raise ValueError("`linestyle=%s` is not in the styles: %s!" % (str(use_linestyle), str(linestyles)))
# check if linestyle is set right
for use_linestyle in use_linestyles:
if use_linestyle not in linestyles:
# raise error
raise ValueError("`linestyle=%s` is not in the styles: %s!" % (str(use_linestyle), str(linestyles)))
# single plot figure
plt.subplot(1, 2, 1)
for index, (use_label, array) in enumerate(dict_arrays.items()):
# set steps plotted on x-axis - we can use step if 1 unit has different value
steps = np.array(range(1, len(array) + 1)) * step_size
# plot array as a single line
plt.plot(steps, array, linestyle=use_linestyles[index], label=use_label)
# set steps plotted on x-axis - we can use step if 1 unit has different value
steps = np.array(range(1, len(array) + 1)) * step_size
# plot array as a single line
plt.plot(steps, array, linestyle=use_linestyles[index], label=use_label)
# Plots points values
if points_values:
# Loop through each point and plot the label.
for x, y in zip(steps, array):
# Add text label to plo.
plt.text(x, y, str(y))
# set title of figure
plt.title(use_title)
# set horizontal axis name
@@ -162,7 +242,7 @@ def plot_dict(dict_arrays, step_size=1, use_title=None, use_xlabel=None, use_yla
# set vertical axis name
plt.ylabel(use_ylabel)
# place legend best position
plt.legend(loc='best')
plt.legend(loc='best') if use_label is not None else None
# display grid depending on `use_grid`
plt.grid(use_grid)
# make figure nice
@@ -176,7 +256,7 @@ def plot_dict(dict_arrays, step_size=1, use_title=None, use_xlabel=None, use_yla
# set the new figure size with magnify
fig.set_size_inches(figsize)
# save figure to image if path is set
fig.savefig(path, dpi=use_dpi) if path is not None else None
fig.savefig(path, dpi=use_dpi, bbox_inches='tight') if path is not None else None
# show plot
plt.show() if show_plot is True else None
@@ -189,11 +269,6 @@ def plot_confusion_matrix(y_true, y_pred, title=None, use_title=None, classes=''
"""This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
y_true needs to contain all possible labels.
:param path: str path to save plot in an image.
:param use_dpi: int clarity of plot.
:param height:
:param width:
:param title: Deprecated!
:param y_true: array labels values.
:param y_pred: array predicted label values.
:param classes: array list of label names.
@@ -245,9 +320,7 @@ def plot_confusion_matrix(y_true, y_pred, title=None, use_title=None, classes=''
assert len(set(y_true)) == len(classes)
else:
classes = set(y_true)
# Compute confusion matrix
cm = confusion_matrix(y_true, y_pred)
# Normalize setup
# Nromalize setup
if normalize is True:
print("Normalized confusion matrix")
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
@@ -255,6 +328,8 @@ def plot_confusion_matrix(y_true, y_pred, title=None, use_title=None, classes=''
else:
print('Confusion matrix, without normalization')
use_title = 'Confusion matrix, without normalization' if use_title is None else use_title
# Compute confusion matrix
cm = confusion_matrix(y_true, y_pred)
# Print if verbose
print(cm) if verbose > 0 else None
# Plot setup
@@ -294,6 +369,6 @@ def plot_confusion_matrix(y_true, y_pred, title=None, use_title=None, classes=''
# set the new figure size with magnify
fig.set_size_inches(figsize)
# save figure to image if path is set
fig.savefig(path, dpi=use_dpi) if path is not None else None
fig.savefig(path, dpi=use_dpi, bbox_inches='tight') if path is not None else None
return cm