From 1432d4fcd24a69a53a512d8a6fb4cdd60ada83ac Mon Sep 17 00:00:00 2001 From: Jan Benda Date: Sat, 4 Jan 2020 13:38:40 +0100 Subject: [PATCH] [regression] updated plot formats --- plotstyle.py | 25 ++++++--- regression/lecture/cubicerrors.py | 18 +++---- regression/lecture/cubicfunc.py | 10 ++-- regression/lecture/cubicmse.py | 14 ++--- regression/lecture/derivative.py | 16 +++--- regression/lecture/error_surface.py | 13 +++-- regression/lecture/gradient.py | 12 ++--- regression/lecture/lin_regress.py | 62 ++++++++-------------- regression/lecture/linear_least_squares.py | 44 ++++++--------- 9 files changed, 93 insertions(+), 121 deletions(-) diff --git a/plotstyle.py b/plotstyle.py index ae13d03..b363b19 100644 --- a/plotstyle.py +++ b/plotstyle.py @@ -149,22 +149,31 @@ def show_spines(ax, spines): ax.yaxis.set_ticks_position('both') -def set_xlabel(ax, label, unit=None): +def set_xlabel(ax, label, unit=None, **kwargs): if not unit: - ax.set_xlabel(label) + ax.set_xlabel(label, **kwargs) elif xkcd_style: - ax.set_xlabel('%s / %s' % (label, unit)) + ax.set_xlabel('%s / %s' % (label, unit), **kwargs) else: - ax.set_xlabel('%s [%s]' % (label, unit)) + ax.set_xlabel('%s [%s]' % (label, unit), **kwargs) -def set_ylabel(ax, label, unit=None): +def set_ylabel(ax, label, unit=None, **kwargs): if not unit: - ax.set_ylabel(label) + ax.set_ylabel(label, **kwargs) elif xkcd_style: - ax.set_ylabel('%s / %s' % (label, unit)) + ax.set_ylabel('%s / %s' % (label, unit), **kwargs) else: - ax.set_ylabel('%s [%s]' % (label, unit)) + ax.set_ylabel('%s [%s]' % (label, unit), **kwargs) + + +def set_zlabel(ax, label, unit=None, **kwargs): + if not unit: + ax.set_zlabel(label, **kwargs) + elif xkcd_style: + ax.set_zlabel('%s / %s' % (label, unit), **kwargs) + else: + ax.set_zlabel('%s [%s]' % (label, unit), **kwargs) # initialization: diff --git a/regression/lecture/cubicerrors.py b/regression/lecture/cubicerrors.py index 7904121..de8ba0d 100644 --- a/regression/lecture/cubicerrors.py +++ b/regression/lecture/cubicerrors.py @@ -1,6 +1,6 @@ import matplotlib.pyplot as plt import numpy as np -from plotstyle import colors, show_spines +from plotstyle import * def create_data(): # wikipedia: @@ -23,8 +23,8 @@ def plot_data(ax, x, y, c): ax.plot(xx, cc*xx**3.0, color=colors['orange'], lw=1.5, zorder=5) show_spines(ax, 'lb') - ax.set_xlabel('Size x / m') - ax.set_ylabel('Weight y / kg') + set_xlabel(ax, 'Size x', 'm') + set_ylabel(ax, 'Weight y', 'kg') ax.set_xlim(2, 4) ax.set_ylim(0, 400) ax.set_xticks(np.arange(2.0, 4.1, 0.5)) @@ -33,8 +33,8 @@ def plot_data(ax, x, y, c): def plot_data_errors(ax, x, y, c): show_spines(ax, 'lb') - ax.set_xlabel('Size x / m') - #ax.set_ylabel('Weight y / kg') + set_xlabel(ax, 'Size x', 'm') + #set_ylabel(ax, 'Weight y', 'kg') ax.set_xlim(2, 4) ax.set_ylim(0, 400) ax.set_xticks(np.arange(2.0, 4.1, 0.5)) @@ -57,8 +57,8 @@ def plot_data_errors(ax, x, y, c): def plot_error_hist(ax, x, y, c): show_spines(ax, 'lb') - ax.set_xlabel('Squared error') - ax.set_ylabel('Frequency') + set_xlabel(ax, 'Squared error') + set_ylabel(ax, 'Frequency') bins = np.arange(0.0, 1250.0, 100) ax.set_xlim(bins[0], bins[-1]) #ax.set_ylim(0, 35) @@ -77,10 +77,10 @@ def plot_error_hist(ax, x, y, c): if __name__ == "__main__": x, y, c = create_data() - fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(7., 2.6)) + fig, (ax1, ax2) = plt.subplots(1, 2) + fig.subplots_adjust(wspace=0.2, **adjust_fs(left=6.0, right=1.2)) plot_data(ax1, x, y, c) plot_data_errors(ax2, x, y, c) #plot_error_hist(ax2, x, y, c) - fig.tight_layout() fig.savefig("cubicerrors.pdf") plt.close() diff --git a/regression/lecture/cubicfunc.py b/regression/lecture/cubicfunc.py index d258723..55e4da1 100644 --- a/regression/lecture/cubicfunc.py +++ b/regression/lecture/cubicfunc.py @@ -1,6 +1,6 @@ import matplotlib.pyplot as plt import numpy as np -from plotstyle import colors, show_spines +from plotstyle import * if __name__ == "__main__": # wikipedia: @@ -13,7 +13,8 @@ if __name__ == "__main__": noise = rng.randn(len(x))*50 y += noise - fig, ax = plt.subplots(figsize=(7., 3.6)) + fig, ax = plt.subplots(figsize=cm_size(figure_width, 1.4*figure_height)) + fig.subplots_adjust(**adjust_fs(left=6.0, right=1.2)) ax.scatter(x, y, marker='o', color=colors['blue'], s=40, zorder=10) xx = np.linspace(2.1, 3.9, 100) @@ -22,13 +23,12 @@ if __name__ == "__main__": ax.plot(xx, cc*xx**3.0, color=colors['orange'], lw=2, zorder=5) show_spines(ax, 'lb') - ax.set_xlabel('Size x / m') - ax.set_ylabel('Weight y / kg') + set_xlabel(ax, 'Size x', 'm') + set_ylabel(ax, 'Weight y', 'kg') ax.set_xlim(2, 4) ax.set_ylim(0, 400) ax.set_xticks(np.arange(2.0, 4.1, 0.5)) ax.set_yticks(np.arange(0, 401, 100)) - fig.subplots_adjust(0.11, 0.16, 0.98, 0.97) fig.savefig("cubicfunc.pdf") plt.close() diff --git a/regression/lecture/cubicmse.py b/regression/lecture/cubicmse.py index dd96e98..31d1be0 100644 --- a/regression/lecture/cubicmse.py +++ b/regression/lecture/cubicmse.py @@ -1,6 +1,6 @@ import matplotlib.pyplot as plt import numpy as np -from plotstyle import colors, show_spines +from plotstyle import * def create_data(): # wikipedia: @@ -51,8 +51,8 @@ def plot_mse(ax, x, y, c, cs): show_spines(ax, 'lb') - ax.set_xlabel('c') - ax.set_ylabel('mean squared error') + set_xlabel(ax, 'c') + set_ylabel(ax, 'Mean squared error') ax.set_xlim(0, 10) ax.set_ylim(0, 25000) ax.set_xticks(np.arange(0.0, 10.1, 2.0)) @@ -62,8 +62,8 @@ def plot_descent(ax, cs, mses): ax.plot(np.arange(len(mses))+1, mses, '-o', c=colors['red'], mew=0, ms=8) show_spines(ax, 'lb') - ax.set_xlabel('iteration') - #ax.set_ylabel('mean squared error') + set_xlabel(ax, 'Iteration') + #set_ylabel(ax, 'Mean squared error') ax.set_xlim(0, 10.5) ax.set_ylim(0, 25000) ax.set_xticks(np.arange(0.0, 10.1, 2.0)) @@ -74,9 +74,9 @@ def plot_descent(ax, cs, mses): if __name__ == "__main__": x, y, c = create_data() cs, mses = gradient_descent(x, y) - fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(7., 2.6)) + fig, (ax1, ax2) = plt.subplots(1, 2) + fig.subplots_adjust(wspace=0.2, **adjust_fs(left=7.5, right=0.5)) plot_mse(ax1, x, y, c, cs) plot_descent(ax2, cs, mses) - fig.tight_layout() fig.savefig("cubicmse.pdf") plt.close() diff --git a/regression/lecture/derivative.py b/regression/lecture/derivative.py index 7d85716..e5d4ea0 100644 --- a/regression/lecture/derivative.py +++ b/regression/lecture/derivative.py @@ -1,7 +1,7 @@ import numpy as np import matplotlib.pyplot as plt +from plotstyle import * -#plt.xkcd() fig = plt.figure( figsize=(2.5,3.4) ) ax = fig.add_subplot(1, 1, 1) @@ -12,7 +12,7 @@ x = np.linspace(x1, x2, 200) y = x*x ax.set_xlim(x1, x2) ax.set_ylim(-0.2, 0.7) -ax.plot(x, y, c='b', lw=4, zorder=0) +ax.plot(x, y, c=colors['blue'], lw=4, zorder=0) # secant: x = np.asarray([0.1, 0.7]) y = x*x @@ -20,7 +20,7 @@ ax.set_xticks(x) ax.set_yticks(y) ax.set_xticklabels(['$x$','$x+\Delta x$']) ax.set_yticklabels(['','']) -ax.scatter(x, y, c='#CC0000', edgecolor='none', s=150, zorder=10) +ax.scatter(x, y, c=colors['red'], edgecolor='none', s=150, zorder=10) # function values: ax.plot([x[0], x[0], x1],[-0.2, y[0], y[0]], '--k', lw=1, zorder=6) ax.plot([x[1], x[1], x1],[-0.2, y[1], y[1]], '--k', lw=1, zorder=6) @@ -34,20 +34,20 @@ ax.text(x[1]+0.05, np.mean(y), '$f(x+\Delta x)-f(x)$', va='center', rotation='ve m = np.diff(y)/np.diff(x) xl = [x1, x2] yl = m*(xl-x[0])+y[0] -ax.plot(xl, yl, c='#CC0000', lw=3, zorder=7) +ax.plot(xl, yl, c=colors['red'], lw=3, zorder=7) # derivative: md = 2.0*x[0] yl = md*(xl-x[0])+y[0] -ax.plot(xl, yl, c='#FFFF66', lw=3, zorder=5) +ax.plot(xl, yl, c=colors['yellow'], lw=3, zorder=5) # limit: for ml in np.linspace(md, m, 5)[1:] : yl = ml*(xl-x[0])+y[0] xs = 0.5*(ml+np.sqrt(ml*ml-4.0*(ml*x[0]-y[0]))) - ax.scatter([xs], [xs*xs], c='#FFCC00', edgecolor='none', s=80, zorder=3) - ax.plot(xl, yl, c='#FFCC00', lw=2, zorder=3) + ax.scatter([xs], [xs*xs], c=colors['orange'], edgecolor='none', s=80, zorder=3) + ax.plot(xl, yl, c=colors['orange'], lw=2, zorder=3) -plt.tight_layout(); +fig.subplots_adjust(**adjust_fs(fig, 0.5, 0.5, 1.4, 0.5)) plt.savefig('derivative.pdf') #plt.show(); diff --git a/regression/lecture/error_surface.py b/regression/lecture/error_surface.py index 30ca2f6..081776f 100644 --- a/regression/lecture/error_surface.py +++ b/regression/lecture/error_surface.py @@ -1,7 +1,8 @@ +import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import matplotlib.cm as cm -import numpy as np +from plotstyle import * def create_data(): m = 0.75 @@ -15,9 +16,9 @@ def create_data(): def plot_error_plane(ax, x, y, m, n): - ax.set_xlabel('Slope m') - ax.set_ylabel('Intercept b') - ax.set_zlabel('Mean squared error') + set_xlabel(ax, 'Slope m') + set_ylabel(ax, 'Intercept b') + set_zlabel(ax, 'Mean squared error') ax.set_xlim(-4.5, 5.0) ax.set_ylim(-60.0, -20.0) ax.set_zlim(0.0, 700.0) @@ -46,12 +47,10 @@ def plot_error_plane(ax, x, y, m, n): if __name__ == "__main__": x, y, m, n = create_data() - plt.xkcd() fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection='3d') plot_error_plane(ax, x, y, m, n) - #fig.set_facecolor("white") fig.set_size_inches(7., 5.) - fig.tight_layout() + fig.subplots_adjust(**adjust_fs(fig, 1.0, 0.0, 0.0, 0.0)) fig.savefig("error_surface.pdf") plt.close() diff --git a/regression/lecture/gradient.py b/regression/lecture/gradient.py index 5f1d35c..1028091 100644 --- a/regression/lecture/gradient.py +++ b/regression/lecture/gradient.py @@ -1,9 +1,9 @@ import numpy as np import matplotlib.pyplot as plt +from plotstyle import * -#plt.xkcd() -fig = plt.figure( figsize=(3.5,3.7) ) -ax = fig.add_subplot(1, 1, 1) +fig, ax = plt.subplots( figsize=(3.5,3.7) ) +fig.subplots_adjust(**adjust_fs(fig, 4.0, 1.0, 2.8, 0.5)) def gaussian(x, y) : return np.exp(-0.5*(x*x+y*y)) @@ -18,8 +18,8 @@ x = np.linspace(x1, x2, 200) y = np.linspace(x1, x2, 200) X, Y = np.meshgrid(x, y) Z = gaussian(X, Y) -ax.set_xlabel('x') -ax.set_ylabel('y', rotation='horizontal') +set_xlabel(ax, 'x') +set_ylabel(ax, 'y', rotation='horizontal') ax.set_xticks(np.arange(x1, x2+0.1, 1.0)) ax.set_yticks(np.arange(x1, x2+0.1, 1.0)) ax.contour(X, Y, Z, linewidths=2, zorder=0) @@ -37,6 +37,4 @@ ax.text(-0.8, -1.5, '$\partial f/\partial x$', ha='center', zorder=20) ax.text(-1.55, -0.8, '$\partial f/\partial y$', va='center', rotation='vertical', zorder=20) ax.text(-0.4, -0.8, r'$\nabla f$', ha='left', zorder=20) -plt.tight_layout(); plt.savefig('gradient.pdf') -#plt.show(); diff --git a/regression/lecture/lin_regress.py b/regression/lecture/lin_regress.py index c50a732..9cf3233 100644 --- a/regression/lecture/lin_regress.py +++ b/regression/lecture/lin_regress.py @@ -1,5 +1,6 @@ -import matplotlib.pyplot as plt import numpy as np +import matplotlib.pyplot as plt +from plotstyle import * def create_data(): m = 0.75 @@ -13,15 +14,10 @@ def create_data(): def plot_data(ax, x, y): - ax.scatter(x, y, marker='o', color='b', s=40) - ax.spines["right"].set_visible(False) - ax.spines["top"].set_visible(False) - ax.yaxis.set_ticks_position('left') - ax.xaxis.set_ticks_position('bottom') - ax.tick_params(direction="out", width=1.25) - ax.tick_params(direction="out", width=1.25) - ax.set_xlabel('Input x') - ax.set_ylabel('Output y') + ax.scatter(x, y, marker='o', color=colors['blue'], s=40) + show_spines(ax, 'lb') + set_xlabel(ax, 'Input x') + set_ylabel(ax, 'Output y') ax.set_xlim(0, 120) ax.set_ylim(-80, 80) ax.set_xticks(np.arange(0,121, 40)) @@ -29,18 +25,13 @@ def plot_data(ax, x, y): def plot_data_slopes(ax, x, y, m, n): - ax.scatter(x, y, marker='o', color='b', s=40) + ax.scatter(x, y, marker='o', color=colors['blue'], s=40) xx = np.asarray([2, 118]) for i in np.linspace(0.3*m, 2.0*m, 5): - ax.plot(xx, i*xx+n, color='#CC0000', lw=2) - ax.spines["right"].set_visible(False) - ax.spines["top"].set_visible(False) - ax.yaxis.set_ticks_position('left') - ax.xaxis.set_ticks_position('bottom') - ax.tick_params(direction="out", width=1.25) - ax.tick_params(direction="out", width=1.25) - ax.set_xlabel('Input x') - #ax.set_ylabel('Output y') + ax.plot(xx, i*xx+n, color=colors['red'], lw=2) + show_spines(ax, 'lb') + set_xlabel(ax, 'Input x') + #set_ylabel(ax, 'Output y') ax.set_xlim(0, 120) ax.set_ylim(-80, 80) ax.set_xticks(np.arange(0,121, 40)) @@ -48,18 +39,13 @@ def plot_data_slopes(ax, x, y, m, n): def plot_data_intercepts(ax, x, y, m, n): - ax.scatter(x, y, marker='o', color='b', s=40) + ax.scatter(x, y, marker='o', color=colors['blue'], s=40) xx = np.asarray([2, 118]) for i in np.linspace(n-1*n, n+1*n, 5): - ax.plot(xx, m*xx + i, color='#CC0000', lw=2) - ax.spines["right"].set_visible(False) - ax.spines["top"].set_visible(False) - ax.yaxis.set_ticks_position('left') - ax.xaxis.set_ticks_position('bottom') - ax.tick_params(direction="out", width=1.25) - ax.tick_params(direction="out", width=1.25) - ax.set_xlabel('Input x') - #ax.set_ylabel('Output y') + ax.plot(xx, m*xx + i, color=colors['red'], lw=2) + show_spines(ax, 'lb') + set_xlabel(ax, 'Input x') + #set_ylabel(ax, 'Output y') ax.set_xlim(0, 120) ax.set_ylim(-80, 80) ax.set_xticks(np.arange(0,121, 40)) @@ -68,16 +54,10 @@ def plot_data_intercepts(ax, x, y, m, n): if __name__ == "__main__": x, y, m, n = create_data() - plt.xkcd() - fig = plt.figure() - ax = fig.add_subplot(1, 3, 1) - plot_data(ax, x, y) - ax = fig.add_subplot(1, 3, 2) - plot_data_slopes(ax, x, y, m, n) - ax = fig.add_subplot(1, 3, 3) - plot_data_intercepts(ax, x, y, m, n) - fig.set_facecolor("white") - fig.set_size_inches(7., 2.6) - fig.tight_layout() + fig, axs = plt.subplots(1, 3) + fig.subplots_adjust(wspace=0.5, **adjust_fs(fig, left=6.0, right=1.5)) + plot_data(axs[0], x, y) + plot_data_slopes(axs[1], x, y, m, n) + plot_data_intercepts(axs[2], x, y, m, n) fig.savefig("lin_regress.pdf") plt.close() diff --git a/regression/lecture/linear_least_squares.py b/regression/lecture/linear_least_squares.py index 1a73991..43e0ea8 100644 --- a/regression/lecture/linear_least_squares.py +++ b/regression/lecture/linear_least_squares.py @@ -1,5 +1,6 @@ -import matplotlib.pyplot as plt import numpy as np +import matplotlib.pyplot as plt +from plotstyle import * def create_data(): m = 0.75 @@ -13,14 +14,9 @@ def create_data(): def plot_data(ax, x, y, m, n): - ax.spines["right"].set_visible(False) - ax.spines["top"].set_visible(False) - ax.yaxis.set_ticks_position('left') - ax.xaxis.set_ticks_position('bottom') - ax.tick_params(direction="out", width=1.25) - ax.tick_params(direction="out", width=1.25) - ax.set_xlabel('Input x') - ax.set_ylabel('Output y') + show_spines(ax, 'lb') + set_xlabel(ax, 'Input x') + set_ylabel(ax, 'Output y') ax.set_xlim(0, 120) ax.set_ylim(-80, 80) ax.set_xticks(np.arange(0,121, 40)) @@ -30,24 +26,19 @@ def plot_data(ax, x, y, m, n): xytext=(80, -50), textcoords='data', ha='left', arrowprops=dict(arrowstyle="->", relpos=(0.9,1.0), connectionstyle="angle3,angleA=50,angleB=-30") ) - ax.scatter(x[:40], y[:40], color='b', s=10, zorder=0) + ax.scatter(x[:40], y[:40], color=colors['blue'], s=10, zorder=0) inxs = [3, 13, 16, 19, 25, 34, 36] - ax.scatter(x[inxs], y[inxs], color='b', s=40, zorder=10) + ax.scatter(x[inxs], y[inxs], color=colors['blue'], s=40, zorder=10) xx = np.asarray([2, 118]) - ax.plot(xx, m*xx+n, color='#CC0000', lw=2) + ax.plot(xx, m*xx+n, color=colors['red'], lw=2) for i in inxs : xx = [x[i], x[i]] yy = [m*x[i]+n, y[i]] - ax.plot(xx, yy, color='#FF9900', lw=2, zorder=5) + ax.plot(xx, yy, color=colors['orange'], lw=2, zorder=5) def plot_error_hist(ax, x, y, m, n): - ax.spines["right"].set_visible(False) - ax.spines["top"].set_visible(False) - ax.yaxis.set_ticks_position('left') - ax.xaxis.set_ticks_position('bottom') - ax.tick_params(direction="out", width=1.25) - ax.tick_params(direction="out", width=1.25) + show_spines(ax, 'lb') ax.set_xlabel('Squared error') ax.set_ylabel('Frequency') bins = np.arange(0.0, 602.0, 50.0) @@ -62,20 +53,15 @@ def plot_error_hist(ax, x, y, m, n): xytext=(350, 20), textcoords='data', ha='left', arrowprops=dict(arrowstyle="->", relpos=(0.0,0.2), connectionstyle="angle3,angleA=10,angleB=90") ) - ax.hist(errors, bins, color='#FF9900') + ax.hist(errors, bins, color=colors['orange']) if __name__ == "__main__": x, y, m, n = create_data() - plt.xkcd() - fig = plt.figure() - ax = fig.add_subplot(1, 2, 1) - plot_data(ax, x, y, m, n) - ax = fig.add_subplot(1, 2, 2) - plot_error_hist(ax, x, y, m, n) - fig.set_facecolor("white") - fig.set_size_inches(7., 2.6) - fig.tight_layout() + fig, axs = plt.subplots(1, 2) + fig.subplots_adjust(**adjust_fs(fig, left=6.0)) + plot_data(axs[0], x, y, m, n) + plot_error_hist(axs[1], x, y, m, n) fig.savefig("linear_least_squares.pdf") plt.close()