diff --git a/plotstyle.py b/plotstyle.py index 7c85d36..729962d 100644 --- a/plotstyle.py +++ b/plotstyle.py @@ -2,8 +2,12 @@ import matplotlib as mpl import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D +# Set to true if you want xkcd-type sketchy plots: xkcd_style = True +# matplotlib major version: +mpl_major = int(mpl.__version__.split('.')[0]) + # default size of figure: figure_width = 15.0 # cm, should be set according to \textwidth in the latex document figure_height = 6.0 # cm, for a 1 x 2 figure @@ -26,7 +30,7 @@ colors['white'] = '#FFFFFF' #colors_bendalab_vivid['green'] = '#30D700' #colors_bendalab_vivid['blue'] = '#0020C0' -# line styles for plot(): +# general settings for plot styles: lwthick = 3.0 lwthin = 1.8 mainline = {'linestyle': '-', 'linewidth': lwthick} @@ -35,9 +39,12 @@ largemarker = {'marker': 'o', 'markersize': 9, 'markeredgecolor': colors['white' smallmarker = {'marker': 'o', 'markersize': 6, 'markeredgecolor': colors['white'], 'markeredgewidth': 1} largelinepoints = {'linestyle': '-', 'linewidth': lwthick, 'marker': 'o', 'markersize': 10, 'markeredgecolor': colors['white'], 'markeredgewidth': 1} smalllinepoints = {'linestyle': '-', 'linewidth': 1.4, 'marker': 'o', 'markersize': 7, 'markeredgecolor': colors['white'], 'markeredgewidth': 1} -filllw = 1 +filllw = 1.0 fillec = colors['white'] fillalpha = 0.4 +filledge = {'linewidth': filllw, 'joinstyle': 'round'} +if int(mpl.__version__.split('.')[0]) < 2: + del filledge['joinstyle'] # helper lines: lsSpine = {'c': colors['black'], 'linestyle': '-', 'linewidth': 1, 'clip_on': False} @@ -71,7 +78,7 @@ psA = dict({'color': colors['blue'], 'linestyle': 'none'}, **largemarker) psAm = dict({'color': colors['blue'], 'linestyle': 'none'}, **smallmarker) lpsA = dict({'color': colors['blue']}, **largelinepoints) lpsAm = dict({'color': colors['blue']}, **smalllinepoints) -fsA = {'facecolor': colors['blue'], 'edgecolor': fillec, 'linewidth': filllw} +fsA = dict({'facecolor': colors['blue'], 'edgecolor': fillec}, **filledge) fsAs = {'facecolor': colors['blue'], 'edgecolor': 'none'} fsAa = {'facecolor': colors['blue'], 'edgecolor': 'none', 'alpha': fillalpha} @@ -81,7 +88,7 @@ psB = dict({'color': colors['red'], 'linestyle': 'none'}, **largemarker) psBm = dict({'color': colors['red'], 'linestyle': 'none'}, **smallmarker) lpsB = dict({'color': colors['red']}, **largelinepoints) lpsBm = dict({'color': colors['red']}, **smalllinepoints) -fsB = {'facecolor': colors['red'], 'edgecolor': fillec, 'linewidth': filllw} +fsB = dict({'facecolor': colors['red'], 'edgecolor': fillec}, **filledge) fsBs = {'facecolor': colors['red'], 'edgecolor': 'none'} fsBa = {'facecolor': colors['red'], 'edgecolor': 'none', 'alpha': fillalpha} @@ -89,7 +96,7 @@ lsC = dict({'color': colors['lightorange']}, **mainline) lsCm = dict({'color': colors['lightorange']}, **minorline) psC = dict({'color': colors['lightorange'], 'linestyle': 'none'}, **largemarker) psCm = dict({'color': colors['lightorange'], 'linestyle': 'none'}, **smallmarker) -fsC = {'facecolor': colors['lightorange'], 'edgecolor': fillec, 'linewidth': filllw} +fsC = dict({'facecolor': colors['lightorange'], 'edgecolor': fillec}, **filledge) fsCs = {'facecolor': colors['lightorange'], 'edgecolor': 'none'} fsCa = {'facecolor': colors['lightorange'], 'edgecolor': 'none', 'alpha': fillalpha} @@ -97,17 +104,17 @@ lsD = dict({'color': colors['orange']}, **mainline) lsDm = dict({'color': colors['orange']}, **minorline) psD = dict({'color': colors['orange'], 'linestyle': 'none'}, **largemarker) psDm = dict({'color': colors['orange'], 'linestyle': 'none'}, **smallmarker) -fsD = {'facecolor': colors['orange'], 'edgecolor': fillec, 'linewidth': filllw} +fsD = dict({'facecolor': colors['orange'], 'edgecolor': fillec}, **filledge) fsDs = {'facecolor': colors['orange'], 'edgecolor': 'none'} lsE = dict({'color': colors['yellow']}, **mainline) lsEm = dict({'color': colors['yellow']}, **minorline) psE = dict({'color': colors['yellow'], 'linestyle': 'none'}, **largemarker) psEm = dict({'color': colors['yellow'], 'linestyle': 'none'}, **smallmarker) -fsE = {'facecolor': colors['yellow'], 'edgecolor': fillec, 'linewidth': filllw} +fsE = dict({'facecolor': colors['yellow'], 'edgecolor': fillec}, **filledge) fsEs = {'facecolor': colors['yellow'], 'edgecolor': 'none'} -fsF = {'facecolor': colors['green'], 'edgecolor': fillec, 'linewidth': filllw} +fsF = dict({'facecolor': colors['green'], 'edgecolor': fillec}, **filledge) fsFs = {'facecolor': colors['green'], 'edgecolor': 'none'} # factor for scaling widths of bars in a bar plot: @@ -326,7 +333,7 @@ def set_zlabel(ax, label, unit=None, **kwargs): ax.set_zlabel_orig(axis_label(label, unit), **kwargs) -def common_format(): +def common_style(): """ Set some rc parameter. """ mpl.rcParams['figure.figsize'] = cm_size(figure_width, figure_height) @@ -337,6 +344,8 @@ def common_format(): mpl.rcParams['figure.subplot.wspace'] = 0.4 mpl.rcParams['figure.subplot.hspace'] = 0.6 mpl.rcParams['figure.facecolor'] = 'white' + mpl.rcParams['figure.edgecolor'] = 'none' + mpl.rcParams['figure.frameon'] = False mpl.rcParams['xtick.direction'] = 'out' mpl.rcParams['ytick.direction'] = 'out' mpl.rcParams['xtick.major.width'] = 1.25 @@ -380,7 +389,7 @@ def sketch_style(): global bar_fac bar_fac = 0.9 plt.xkcd() - common_format() + common_style() mpl.rcParams['legend.fontsize'] = 'medium' mpl.rcParams['xtick.labelsize'] = 'medium' mpl.rcParams['ytick.labelsize'] = 'medium' @@ -394,7 +403,7 @@ def plain_style(): global bar_fac bar_fac = 1.0 plt.rcdefaults() - common_format() + common_style() mpl.rcParams['font.family'] = 'sans-serif' mpl.rcParams['legend.fontsize'] = 'x-small' mpl.rcParams['xtick.labelsize'] = 'small' diff --git a/statistics/lecture/diehistograms.py b/statistics/lecture/diehistograms.py index c5d03fb..2458412 100644 --- a/statistics/lecture/diehistograms.py +++ b/statistics/lecture/diehistograms.py @@ -2,7 +2,6 @@ import numpy as np import matplotlib.pyplot as plt from plotstyle import * -sketch_style() # roll the die: rng = np.random.RandomState(57281) x1 = rng.randint(1, 7, 100) @@ -27,9 +26,9 @@ ax2.set_xlabel('x') ax2.set_ylim(0, 0.23) ax2.set_ylabel('Probability') ax2.plot([0.2, 6.8], [1.0/6.0, 1.0/6.0], zorder=-10, **lsAm) -try: +if mpl_major > 1: ax2.hist([x2, x1], bins, density=True, zorder=-5, **fs) -except AttributeError: +else: ax2.hist([x2, x1], bins, normed=True, zorder=-5, **fs) fig.subplots_adjust(left=0.125) fig.savefig('diehistograms.pdf') diff --git a/statistics/lecture/displayunivariatedata.py b/statistics/lecture/displayunivariatedata.py index f56906a..64604c0 100644 --- a/statistics/lecture/displayunivariatedata.py +++ b/statistics/lecture/displayunivariatedata.py @@ -4,7 +4,6 @@ import matplotlib.gridspec as gridspec from scipy.stats import gaussian_kde from plotstyle import * -#sketch_style() #rng = np.random.RandomState(981) #data = rng.randn(40, 1) + 4.0 rng = np.random.RandomState(1981) @@ -19,9 +18,11 @@ fig = plt.figure(figsize=cm_size(figure_width, 1.1*figure_height)) spec = gridspec.GridSpec(nrows=1, ncols=2, width_ratios=[3, 1], wspace=0.1, **adjust_fs(fig, left=4.0)) -ax = fig.add_subplot(spec[0, 0]) +ax = fig.add_subplot(spec[0, 0], label='1') wh = ax.boxplot( data, positions=[boxpos], widths=[barwidth], whis=100.0, patch_artist=True) +mediancolor = 'k' wh['medians'][0].set_linewidth(4) +wh['medians'][0].set_color(mediancolor) wh['whiskers'][0].set_linewidth(2) wh['whiskers'][1].set_linewidth(2) wh['whiskers'][0].set_linestyle('-') @@ -34,6 +35,16 @@ wh['caps'][1].set_color(whiskercolor) wh['boxes'][0].set_facecolor('#99ff00') ax.set_xlim(0.0, 4.8) ax.set_ylim( 0.0, 8.0) +ax.set_xticklabels([]) + +ax = fig.add_subplot(spec[0, 0], label='2') +ax.set_xlim(0.0, 4.8) +ax.set_xticks([scatterpos, barpos, boxpos]) +ax.set_xticklabels(['(1) data', '(2) bar\n plot', '(3) box-\nwhisker'], fontsize='medium') +ax.set_ylabel('x') +ax.set_ylim( 0.0, 8.0) + +# annotate box whisker: ax.annotate('maximum', xy=(boxpos, 6.5), xycoords='data', xytext=(boxpos-1*barwidth, 7.6), textcoords='data', ha='left', @@ -49,14 +60,6 @@ ax.annotate('median', xytext=(boxpos+0.1*barwidth, 4.2), textcoords='data', ha='left', arrowprops=dict(arrowstyle="->", relpos=(0.8,0.0), connectionstyle="angle3,angleA=-60,angleB=20") ) -ax.set_xticklabels([]) - -ax = fig.add_subplot(spec[0, 0]) -ax.set_xlim(0.0, 4.8) -ax.set_xticks([scatterpos, barpos, boxpos]) -ax.set_xticklabels(['(1) data', '(2) bar\n plot', '(3) box-\nwhisker'], fontsize='medium') -ax.set_ylabel('x') -ax.set_ylim( 0.0, 8.0) # scatter data points according to their density: kernel = gaussian_kde(data) @@ -67,7 +70,10 @@ ax.plot(scatterpos+barwidth*x*(rng.rand(len(data))-0.5), data, **psA) barmean = np.mean(data) barstd = np.std(data) ew = 0.2 -ax.bar([barpos-0.5*barwidth], [barmean], barwidth, **fsC) +if mpl_major > 1: + ax.bar([barpos], [barmean], barwidth, **fsC) +else: + ax.bar([barpos-0.5*barwidth], [barmean], barwidth, **fsC) ax.plot([barpos, barpos], [barmean-barstd, barmean+barstd], **lsMarker) ax.plot([barpos-0.5*ew, barpos+0.5*ew], [barmean-barstd, barmean-barstd], **lsMarker) ax.plot([barpos-0.5*ew, barpos+0.5*ew], [barmean+barstd, barmean+barstd], **lsMarker) diff --git a/statistics/lecture/kerneldensity.py b/statistics/lecture/kerneldensity.py index 2a0cbb7..503ac46 100644 --- a/statistics/lecture/kerneldensity.py +++ b/statistics/lecture/kerneldensity.py @@ -1,6 +1,7 @@ import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec +import matplotlib.ticker as ticker from plotstyle import * # normal distribution: @@ -37,41 +38,39 @@ spec = gridspec.GridSpec(nrows=2, ncols=2, wspace=0.35, hspace=0.3, **adjust_fs(fig, left=5.5, top=0.2, bottom=2.7)) ax = fig.add_subplot(spec[0, 0]) -ax.set_xlabel('x') ax.set_xlim(-3.2, 3.2) -ax.set_xticks(np.arange(-3.0, 3.1, 1.0)) +ax.xaxis.set_major_locator(ticker.MultipleLocator(1.0)) +ax.xaxis.set_major_formatter(ticker.NullFormatter()) ax.set_ylabel('p(x)') ax.set_ylim(0.0, 0.49) -ax.set_yticks(np.arange(0.0, 0.41, 0.1)) -#ax.plot(x, g, '-b', lw=2, zorder=-1) -try: +ax.yaxis.set_major_locator(ticker.MultipleLocator(0.2)) +if mpl_major > 1: ax.hist(r, np.arange(-4.1, 4, 0.4), density=True, zorder=-5, **fsC) -except AttributeError: +else: ax.hist(r, np.arange(-4.1, 4, 0.4), normed=True, zorder=-5, **fsC) ax = fig.add_subplot(spec[1, 0]) ax.set_xlabel('x') ax.set_xlim(-3.2, 3.2) -ax.set_xticks(np.arange(-3.0, 3.1, 1.0)) +ax.xaxis.set_major_locator(ticker.MultipleLocator(1.0)) ax.set_ylabel('p(x)') ax.set_ylim(0.0, 0.49) -ax.set_yticks(np.arange(0.0, 0.41, 0.1)) -#ax.plot(x, g, '-b', lw=2, zorder=-1) -try: +ax.yaxis.set_major_locator(ticker.MultipleLocator(0.2)) +if mpl_major > 1: ax.hist(r, np.arange(-4.3, 4, 0.4), density=True, zorder=-5, **fsC) -except AttributeError: +else: ax.hist(r, np.arange(-4.3, 4, 0.4), normed=True, zorder=-5, **fsC) ax = fig.add_subplot(spec[:, 1]) ax.set_xlabel('x') ax.set_xlim(-3.2, 3.2) -ax.set_xticks(np.arange(-3.0, 3.1, 1.0)) +ax.xaxis.set_major_locator(ticker.MultipleLocator(1.0)) ax.set_ylabel('Prob. density p(x)') ax.set_ylim(0.0, 0.49) ax.set_yticks(np.arange(0.0, 0.41, 0.1)) kd, xx = kerneldensity(r, -3.2, 3.2, 0.2) ax.fill_between(xx, 0.0, kd, zorder=-5, **fsDs) ax.plot(xx, kd, '-', zorder=-1, **lsB) -fig.subplots_adjust(left=0.15) + fig.savefig('kerneldensity.pdf') diff --git a/statistics/lecture/pdfhistogram.py b/statistics/lecture/pdfhistogram.py index cddffa6..33e6cf4 100644 --- a/statistics/lecture/pdfhistogram.py +++ b/statistics/lecture/pdfhistogram.py @@ -8,7 +8,7 @@ x = np.arange(-4.0, 4.0, 0.01) g = np.exp(-0.5*x*x)/np.sqrt(2.0*np.pi) r = rng.randn(100) -fig, (ax1, ax2) = plt.subplots(1, 2) +fig, (ax1, ax2) = plt.subplots(1, 2, figsize=cm_size(figure_width, 1.1*figure_height)) ax1.set_xlabel('x') ax1.set_xlim(-3.2, 3.2) ax1.set_xticks(np.arange(-3.0, 3.1, 1.0)) @@ -24,10 +24,10 @@ ax2.set_ylabel('Probab. density p(x)') ax2.set_ylim(0.0, 0.44) ax2.set_yticks(np.arange(0.0, 0.41, 0.1)) ax2.plot(x, g, zorder=-1, **lsA) -try: +if mpl_major > 1: ax2.hist(r, 5, density=True, zorder=-10, **fsB) ax2.hist(r, 20, density=True, zorder=-5, **fsC) -except AttributeError: +else: ax2.hist(r, 5, normed=True, zorder=-10, **fsB) ax2.hist(r, 20, normed=True, zorder=-5, **fsC) diff --git a/statistics/lecture/pdfprobabilities.py b/statistics/lecture/pdfprobabilities.py index 3e9e3c6..87928e3 100644 --- a/statistics/lecture/pdfprobabilities.py +++ b/statistics/lecture/pdfprobabilities.py @@ -10,7 +10,7 @@ x2=1.0 fig, ax = plt.subplots(figsize=cm_size(figure_width, 1.2*figure_height)) ax.set_xlabel('x') -ax.set_ylabel('Probability density p(x)') +ax.set_ylabel('Prob. density p(x)') ax.set_ylim(0.0, 0.46) ax.set_yticks(np.arange(0.0, 0.45, 0.1)) ax.annotate('Gaussian',