def test_barplot(): """Test bar plot function """ import matplotlib.pyplot as plt ax = plt.subplot(1, 1, 1) tmp1 = np.arange(4) # 1-Dim tmp2 = np.arange(20).reshape((4, 5)) # 2-Dim ea.barplot(tmp1, err_bars=tmp1, brackets=[(0, 1), (2, 3)], bracket_text=['foo', 'bar'], ax=ax) ea.barplot(tmp1, groups=[[0, 1, 2], [3]], eq_group_widths=True, brackets=[([0], 3)], bracket_text='foo') ea.barplot(tmp2, lines=True, ylim=(0, 2), err_bars='se') ea.barplot(tmp2, groups=[[0, 1], [2, 3]], err_bars='ci', group_names=['foo', 'bar']) extns = ['eps', 'pdf', 'png', 'raw', 'svg'] # jpg, tif not supported for ext in extns: fname = op.join(temp_dir, 'temp.' + ext) ea.barplot(tmp2, groups=[[0, 1, 2], [3]], err_bars='sd', fname=fname) assert_raises(ValueError, ea.barplot, np.arange(8).reshape((2, 2, 2))) assert_raises(ValueError, ea.barplot, tmp2, err_bars='foo') assert_raises(ValueError, ea.barplot, tmp2, gap_size=1.1) assert_raises(ValueError, ea.barplot, tmp1, err_bars=np.arange(3)) assert_raises(ValueError, ea.barplot, tmp1, err_bars='sd') assert_raises(ValueError, ea.barplot, tmp1, brackets=[(0, 1)], bracket_text=['foo', 'bar']) assert_raises(ValueError, ea.barplot, tmp1, brackets=[(1,)], bracket_text=['foo'])
def test_barplot_with_pandas(): """Test bar plot function pandas support""" import pandas as pd tmp = pd.DataFrame(np.arange(20).reshape((4, 5)), columns=['a', 'b', 'c', 'd', 'e'], index=['one', 'two', 'three', 'four']) ea.barplot(tmp) ea.barplot(tmp, axis=0, lines=True)
def test_barplot_multiple(): """Test with multiple data points per bar and calculated ranges.""" import matplotlib.pyplot as plt rng = np.random.RandomState(0) tmp = (rng.randn(20) + np.arange(20)).reshape((5, 4)) # 2-dim _, axs = plt.subplots(1, 4, sharey=False) ea.barplot(tmp, lines=True, err_bars='sd', ax=axs[0], smart_defaults=False) ea.barplot(tmp, lines=True, err_bars='ci', ax=axs[1], axis=0) ea.barplot(tmp, lines=True, err_bars='se', ax=axs[2], ylim=(0, 30)) ea.barplot(tmp, lines=True, err_bars='se', ax=axs[3], groups=[[0, 1, 2], [3, 4]], bracket_group_lines=True, brackets=[(0, 1), (1, 2), (3, 4), ([0, 1, 2], [3, 4])], bracket_text=['foo', 'bar', 'baz', 'snafu']) extns = ['pdf'] # jpg, tif not supported; 'png', 'raw', 'svg' not tested for ext in extns: fname = op.join(temp_dir, 'temp.' + ext) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') ea.barplot(tmp, groups=[[0, 1, 2], [3]], err_bars='sd', axis=0, fname=fname) plt.close() _check_warnings(w) plt.close('all')
c_prob = 0.9 t_prob = 0.6 subjs = ['a', 'b', 'c', 'd', 'e'] ctrl = np.random.binomial(trials, c_prob, len(subjs)) test = np.random.binomial(trials, t_prob, len(subjs)) ctrl_miss = trials - ctrl test_miss = trials - test data = pd.DataFrame(dict(ctrl_hit=ctrl, ctrl_miss=ctrl_miss, test_hit=test, test_miss=test_miss), index=subjs) # calculate dprimes ctrl_dprime = ea.dprime_2afc(data[['ctrl_hit', 'ctrl_miss']]) test_dprime = ea.dprime_2afc(data[['test_hit', 'test_miss']]) results = pd.DataFrame(dict(ctrl=ctrl_dprime, test=test_dprime)) # plot plt.ion() subplt, barplt = ea.barplot(results, axis=0, err_bars='sd', lines=True, brackets=[(0, 1)], bracket_text=[r'$p < 10^{-9}$']) subplt.yaxis.set_label_text('d-prime +/- 1 s.d.') subplt.set_title('Each line represents a different subject') # significance brackets example trials_per_cond = 100 conds = ['ctrl', 'test'] diffs = ['easy', 'hard'] colnames = ['-'.join([x, y]) for x, y in zip(conds * 2, np.tile(diffs, (2, 1)).T.ravel().tolist())] cprob = [0.8, 0.5] dprob = [0.9, 0.6] cblock = np.tile(np.atleast_2d(cprob).T, (2, len(subjs))).T dblock = np.tile(np.atleast_2d(np.repeat(dprob, 2)).T, len(subjs)).T probs = cblock * dblock rawscores = np.random.binomial(trials_per_cond, probs, (len(subjs), len(conds)
# params nreps = 20 lang_order = np.array((0, 2, 1)) # eng, nld, hin feats = ('Continuant', 'Sonorant', 'Del. Rel.', 'Voiced', 'Aspirated', 'Labial', 'Coronal', 'Dorsal') feat_names = ['\n' + n if ix % 2 else n + '\n' for ix, n in enumerate(feats)] # EER matrix dims (from readme): repetition, testLanguage, kFold, feature id_ = loadmat('EER_ID.mat')['EER'] # (50, 3, 4, 8) bars = id_[:nreps].mean(-2) # average over kFold bars = bars[:, lang_order, :] # arrange languages in order: eng, nld, hin bars = bars.swapaxes(-1, -2) # transpose last 2 dims bars = bars.reshape(-1, 24) # flatten last two axes (keep "repetition") # grouping indices groups = np.arange(bars.shape[-1]).reshape(-1, 3) # plot it fig = plt.figure(figsize=(6.5, 2.75)) ax = plt.Axes(fig, [0.1, 0.2, 0.875, 0.7]) fig.add_axes(ax) p, b = barplot(bars, axis=0, err_bars='sd', groups=groups, gap_size=0.5, bar_names='', ylim=(0.2, 0.6), group_names=feat_names, ax=ax, bar_kwargs=dict(color=('0.3', '0.6', '0.9'))) p.yaxis.set_label_text('Equal Error Rate') p.yaxis.set_ticks(np.linspace(0.2, 0.6, 5)) xmin, xmax = p.get_axes().get_xlim() p.hlines(0.5, xmin, xmax, linestyles='--') #plt.tight_layout() ax.legend(b.get_children()[:3], ('English', 'Dutch', 'Hindi'), loc=(0.8, 0.8), fontsize=10) plt.draw() fig.savefig('eer-barplot.pdf')
def test_barplot(): """Test bar plot function """ import matplotlib.pyplot as plt rng = np.random.RandomState(0) # TESTS THAT SHOULD FAIL tmp = np.ones(4) + rng.rand(4) err = 0.1 + tmp / 5. # too many data dimensions: assert_raises(ValueError, ea.barplot, np.arange(8).reshape((2, 2, 2))) # gap_size > 1: assert_raises(ValueError, ea.barplot, tmp, gap_size=1.1) # shape mismatch between data & error bars: assert_raises(ValueError, ea.barplot, tmp, err_bars=np.arange(3)) # bad err_bar string: assert_raises(ValueError, ea.barplot, tmp, err_bars='foo') # cannot calculate 'sd' error bars with only 1 value per bar: assert_raises(ValueError, ea.barplot, tmp, err_bars='sd') # mismatched lengths of brackets & bracket_text: assert_raises(ValueError, ea.barplot, tmp, brackets=[(0, 1)], bracket_text=['foo', 'bar']) # bad bracket spec: assert_raises(ValueError, ea.barplot, tmp, brackets=[(1, )], bracket_text=['foo']) # TEST WITH SINGLE DATA POINT & SINGLE ERROR BAR SPEC. ea.barplot(2, err_bars=0.2) # TESTS WITH ONE DATA POINT PER BAR & USER-SPECIFIED ERROR BAR RANGES _, axs = plt.subplots(1, 5, sharey=False) ea.barplot(tmp, err_bars=err, brackets=([2, 3], [0, 1]), ax=axs[0], bracket_text=['foo', 'bar'], bracket_inline=True) ea.barplot(tmp, err_bars=err, brackets=((0, 2), (1, 3)), ax=axs[1], bracket_text=['foo', 'bar']) ea.barplot(tmp, err_bars=err, brackets=[[2, 1], [0, 3]], ax=axs[2], bracket_text=['foo', 'bar']) ea.barplot(tmp, err_bars=err, brackets=[(0, 1), (0, 2), (0, 3)], bracket_text=['foo', 'bar', 'baz'], ax=axs[3]) ea.barplot(tmp, err_bars=err, brackets=[(0, 1), (2, 3), (0, 2), (1, 3)], bracket_text=['foo', 'bar', 'baz', 'snafu'], ax=axs[4]) ea.barplot(tmp, groups=[[0, 1, 2], [3]], eq_group_widths=True, brackets=[(0, 1), (1, 2), ([0, 1, 2], 3)], bracket_text=['foo', 'bar', 'baz'], bracket_group_lines=True) # TESTS WITH MULTIPLE DATA POINTS PER BAR & CALCULATED ERROR BAR RANGES tmp = (rng.randn(20) + np.arange(20)).reshape((5, 4)) # 2-dim _, axs = plt.subplots(1, 4, sharey=False) ea.barplot(tmp, lines=True, err_bars='sd', ax=axs[0], smart_defaults=False) ea.barplot(tmp, lines=True, err_bars='ci', ax=axs[1], axis=0) ea.barplot(tmp, lines=True, err_bars='se', ax=axs[2], ylim=(0, 30)) ea.barplot(tmp, lines=True, err_bars='se', ax=axs[3], groups=[[0, 1, 2], [3, 4]], bracket_group_lines=True, brackets=[(0, 1), (1, 2), (3, 4), ([0, 1, 2], [3, 4])], bracket_text=['foo', 'bar', 'baz', 'snafu']) extns = ['eps', 'pdf', 'png', 'raw', 'svg'] # jpg, tif not supported for ext in extns: fname = op.join(temp_dir, 'temp.' + ext) with warnings.catch_warnings(record=True) as w: ea.barplot(tmp, groups=[[0, 1, 2], [3]], err_bars='sd', axis=0, fname=fname) plt.close() _check_warnings(w)
def test_barplot(): """Test bar plot function """ import matplotlib.pyplot as plt rng = np.random.RandomState(0) ea.barplot(2, err_bars=0.2) # 0-dim tmp = np.ones(4) + rng.rand(4) # 1-dim err = 0.1 + tmp / 5. _, axs = plt.subplots(1, 5, sharey=False) ea.barplot(tmp, err_bars=err, brackets=([2, 3], [0, 1]), ax=axs[0], bracket_text=['foo', 'bar']) ea.barplot(tmp, err_bars=err, brackets=((0, 2), (1, 3)), ax=axs[1], bracket_text=['foo', 'bar']) ea.barplot(tmp, err_bars=err, brackets=[[2, 1], [0, 3]], ax=axs[2], bracket_text=['foo', 'bar']) ea.barplot(tmp, err_bars=err, brackets=[(0, 1), (0, 2), (0, 3)], bracket_text=['foo', 'bar', 'baz'], ax=axs[3]) ea.barplot(tmp, err_bars=err, brackets=[(0, 1), (2, 3), (0, 2), (1, 3)], bracket_text=['foo', 'bar', 'baz', 'snafu'], ax=axs[4]) ea.barplot(tmp, groups=[[0, 1, 2], [3]], eq_group_widths=True, brackets=[(0, 1), (1, 2), ([0, 1, 2], 3)], bracket_text=['foo', 'bar', 'baz'], bracket_group_lines=True) assert_raises(ValueError, ea.barplot, tmp, err_bars=np.arange(3)) assert_raises(ValueError, ea.barplot, tmp, err_bars='sd') assert_raises(ValueError, ea.barplot, tmp, brackets=[(0, 1)], bracket_text=['foo', 'bar']) assert_raises(ValueError, ea.barplot, tmp, brackets=[(1,)], bracket_text=['foo']) tmp = (rng.randn(20) + np.arange(20)).reshape((5, 4)) # 2-dim _, axs = plt.subplots(1, 4, sharey=False) ea.barplot(tmp, lines=True, err_bars='sd', ax=axs[0], smart_defaults=False) ea.barplot(tmp, lines=True, err_bars='ci', ax=axs[1], axis=0) ea.barplot(tmp, lines=True, err_bars='se', ax=axs[2], ylim=(0, 30)) ea.barplot(tmp, lines=True, err_bars='se', ax=axs[3], groups=[[0, 1, 2], [3, 4]], bracket_group_lines=True, brackets=[(0, 1), (1, 2), (3, 4), ([0, 1, 2], [3, 4])], bracket_text=['foo', 'bar', 'baz', 'snafu']) extns = ['eps', 'pdf', 'png', 'raw', 'svg'] # jpg, tif not supported for ext in extns: fname = op.join(temp_dir, 'temp.' + ext) ea.barplot(tmp, groups=[[0, 1, 2], [3]], err_bars='sd', axis=0, fname=fname) assert_raises(ValueError, ea.barplot, np.arange(8).reshape((2, 2, 2))) assert_raises(ValueError, ea.barplot, tmp, err_bars='foo') assert_raises(ValueError, ea.barplot, tmp, gap_size=1.1)
a_miss=a_miss, a_fa=a_fa, a_cr=a_cr, b_hit=b_hit, b_miss=b_miss, b_fa=b_fa, b_cr=b_cr), index=subjs) # calculate dprimes a_dprime = ea.dprime(data[['a_hit', 'a_miss', 'a_fa', 'a_cr']]) b_dprime = ea.dprime(data[['b_hit', 'b_miss', 'b_fa', 'b_cr']]) results = pd.DataFrame(dict(ctrl=a_dprime, test=b_dprime)) # plot subplt, barplt = ea.barplot(results, axis=0, err_bars='sd', lines=True, brackets=[(0, 1)], bracket_text=[r'$p < 10^{-9}$']) subplt.yaxis.set_label_text('d-prime +/- 1 s.d.') subplt.set_title('Each line represents a different subject') # significance brackets example trials_per_cond = 100 conds = ['ctrl', 'test'] diffs = ['easy', 'hard'] colnames = [ '-'.join([x, y]) for x, y in zip(conds * 2, np.tile(diffs, (2, 1)).T.ravel().tolist()) ] cond_prob = [0.9, 0.8] diff_prob = [0.9, 0.7]
def test_barplot(): """Test bar plot function """ import matplotlib.pyplot as plt rng = np.random.RandomState(0) # TESTS THAT SHOULD FAIL tmp = np.ones(4) + rng.rand(4) err = 0.1 + tmp / 5. # too many data dimensions: assert_raises(ValueError, ea.barplot, np.arange(8).reshape((2, 2, 2))) # gap_size > 1: assert_raises(ValueError, ea.barplot, tmp, gap_size=1.1) # shape mismatch between data & error bars: assert_raises(ValueError, ea.barplot, tmp, err_bars=np.arange(3)) # bad err_bar string: assert_raises(ValueError, ea.barplot, tmp, err_bars='foo') # cannot calculate 'sd' error bars with only 1 value per bar: assert_raises(ValueError, ea.barplot, tmp, err_bars='sd') # mismatched lengths of brackets & bracket_text: assert_raises(ValueError, ea.barplot, tmp, brackets=[(0, 1)], bracket_text=['foo', 'bar']) # bad bracket spec: assert_raises(ValueError, ea.barplot, tmp, brackets=[(1,)], bracket_text=['foo']) # TEST WITH SINGLE DATA POINT & SINGLE ERROR BAR SPEC. ea.barplot(2, err_bars=0.2) # TESTS WITH ONE DATA POINT PER BAR & USER-SPECIFIED ERROR BAR RANGES _, axs = plt.subplots(1, 5, sharey=False) ea.barplot(tmp, err_bars=err, brackets=([2, 3], [0, 1]), ax=axs[0], bracket_text=['foo', 'bar'], bracket_inline=True) ea.barplot(tmp, err_bars=err, brackets=((0, 2), (1, 3)), ax=axs[1], bracket_text=['foo', 'bar']) ea.barplot(tmp, err_bars=err, brackets=[[2, 1], [0, 3]], ax=axs[2], bracket_text=['foo', 'bar']) ea.barplot(tmp, err_bars=err, brackets=[(0, 1), (0, 2), (0, 3)], bracket_text=['foo', 'bar', 'baz'], ax=axs[3]) ea.barplot(tmp, err_bars=err, brackets=[(0, 1), (2, 3), (0, 2), (1, 3)], bracket_text=['foo', 'bar', 'baz', 'snafu'], ax=axs[4]) ea.barplot(tmp, groups=[[0, 1, 2], [3]], eq_group_widths=True, brackets=[(0, 1), (1, 2), ([0, 1, 2], 3)], bracket_text=['foo', 'bar', 'baz'], bracket_group_lines=True) # TESTS WITH MULTIPLE DATA POINTS PER BAR & CALCULATED ERROR BAR RANGES tmp = (rng.randn(20) + np.arange(20)).reshape((5, 4)) # 2-dim _, axs = plt.subplots(1, 4, sharey=False) ea.barplot(tmp, lines=True, err_bars='sd', ax=axs[0], smart_defaults=False) ea.barplot(tmp, lines=True, err_bars='ci', ax=axs[1], axis=0) ea.barplot(tmp, lines=True, err_bars='se', ax=axs[2], ylim=(0, 30)) ea.barplot(tmp, lines=True, err_bars='se', ax=axs[3], groups=[[0, 1, 2], [3, 4]], bracket_group_lines=True, brackets=[(0, 1), (1, 2), (3, 4), ([0, 1, 2], [3, 4])], bracket_text=['foo', 'bar', 'baz', 'snafu']) extns = ['eps', 'pdf', 'png', 'raw', 'svg'] # jpg, tif not supported for ext in extns: fname = op.join(temp_dir, 'temp.' + ext) with warnings.catch_warnings(record=True) as w: ea.barplot(tmp, groups=[[0, 1, 2], [3]], err_bars='sd', axis=0, fname=fname) plt.close() _check_warnings(w)
# License: BSD (3-clause) print(__doc__) import numpy as np import pandas as pd import matplotlib.pyplot as plt import expyfun.analyze as ea # simulate some 2AFC data trials = 100 c_prob = 0.9 t_prob = 0.6 subjs = ['a', 'b', 'c', 'd', 'e'] ctrl = np.random.binomial(trials, c_prob, len(subjs)) test = np.random.binomial(trials, t_prob, len(subjs)) ctrl_miss = trials - ctrl test_miss = trials - test data = pd.DataFrame(dict(ctrl_hit=ctrl, ctrl_miss=ctrl_miss, test_hit=test, test_miss=test_miss), index=subjs) # calculate dprimes ctrl_dprime = ea.dprime_2afc(data[['ctrl_hit', 'ctrl_miss']]) test_dprime = ea.dprime_2afc(data[['test_hit', 'test_miss']]) results = pd.DataFrame(dict(ctrl=ctrl_dprime, test=test_dprime)) # plot plt.ion() subplt, barplt = ea.barplot(results, axis=0, err_bars='sd', lines=True, brackets=[(0, 1)], bracket_text=[r'$p < 10^{-9}$']) subplt.yaxis.set_label(u'd-prime ± 1 s.d.') subplt.set_title('Each line represents a different subject')
bar_kw = {'linewidth': 2, 'color': '1'} line_kw = {'color': 'k', 'marker': 'o', 'fillstyle': 'full', 'markersize': 5, 'alpha': 0.3, 'lw': 0} error_kw = {'ecolor': 'k', 'linewidth': 2, 'capsize': 5, 'capthick': 1.25} bracket_kw = {'color': 'k', 'clip_on': False} pval_kwargs = {'fontsize': 10.5} ####################################### # Create figure and plot fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(fig_width_1col * 1.5, 4.5), sharey=True, facecolor='white') fig.subplots_adjust(top=0.75, bottom=0.2, left=0.14, right=0.975) p, b = barplot(data, axis=0, ylim=[45, 70], err_bars='se', lines=False, groups=groups, gap_size=0.4, brackets=brackets, bracket_text=p_val_text, pval_kwargs=pval_kwargs, bracket_group_lines=True, bar_names=bar_labels, bar_kwargs=bar_kw, err_kwargs=error_kw, line_kwargs=line_kw, bracket_kwargs=bracket_kw, ax=ax, smart_defaults=False) ax.axhline(50., c='r', ls='dashed', label='Chance', lw=1.25) ax.set_ylabel('Accuracy (%)', fontsize=label_fontsize + 2) # Add text showing actual scores for mi, mean in enumerate(data_means): bbox = b[mi].get_bbox() xpos = (bbox.x0 + bbox.x1) / 2. ax.annotate('%0.1f' % (mean), xy=(xpos, 47), xycoords=ax.transData, ha='center', va='center', fontsize=9, color='0.35') # Fix ticks and margins ax.locator_params(axis='y', nbins=6)
def test_barplot_single_spec(tmp_err): """Test with one data point per bar and user-specified err ranges.""" import matplotlib.pyplot as plt tmp, err = tmp_err _, axs = plt.subplots(1, 5, sharey=False) ea.barplot(tmp, err_bars=err, brackets=([2, 3], [0, 1]), ax=axs[0], bracket_text=['foo', 'bar'], bracket_inline=True) ea.barplot(tmp, err_bars=err, brackets=((0, 2), (1, 3)), ax=axs[1], bracket_text=['foo', 'bar']) ea.barplot(tmp, err_bars=err, brackets=[[2, 1], [0, 3]], ax=axs[2], bracket_text=['foo', 'bar']) ea.barplot(tmp, err_bars=err, brackets=[(0, 1), (0, 2), (0, 3)], bracket_text=['foo', 'bar', 'baz'], ax=axs[3]) ea.barplot(tmp, err_bars=err, brackets=[(0, 1), (2, 3), (0, 2), (1, 3)], bracket_text=['foo', 'bar', 'baz', 'snafu'], ax=axs[4]) ea.barplot(tmp, groups=[[0, 1, 2], [3]], eq_group_widths=True, brackets=[(0, 1), (1, 2), ([0, 1, 2], 3)], bracket_text=['foo', 'bar', 'baz'], bracket_group_lines=True) plt.close('all')
def test_barplot_single(tmp_err): """Test with single data point and single error bar spec.""" import matplotlib.pyplot as plt tmp, err = tmp_err ea.barplot(2, err_bars=0.2) plt.close('all')