Saturday, February 6, 2010

Bar plot with data points



I saw this here (Cumming 2007 PMID 17420288 ).

There are still a few issues to work out. Most important, I don't know how to specify the limits for the axes. This one looks OK, but it doesn't always come out so, and I haven't been able to find the right call to fix them.

[UPDATE: I forgot all about it! I need to surpress the x-axis labels!]

Another issue is that the error bar thickness doesn't seem to be settable. There's no API (linewidth refers to the bar rather than the error bars), and the objects that come back don't seem to have an appropriate reference. One last detail is that the code for the distance between a set of data points and the bar is not rational. But I think it's not too bad for a novice.

Here is the listing:


import numpy as np
from pylab import *

data1 = np.linspace(12,22,7)
data2 = np.random.normal(loc=15,scale=5,size=10)
data3 = [11,12,18,19,20,26,27]
data = [data1,np.abs(data2),data3]

# n = number of groups
def layout(n,r=7):
s = r**2 # r = radius of each data point
#layout from 1 to 100
margin = 5
spacer = 10
group_width = (100 - 2*margin - (n-1)*spacer)*1.0/n
dot_width = r
bar_width = group_width - dot_width
current = margin
rL = list()
for i in range(n):
rL.append(current) # x for point
rL.append(current + 3) # x for bar
current += group_width + spacer
return s, bar_width, rL

s, w, xlocs = layout(len(data))
for group in data:
x = xlocs.pop(0)
for e in group:
scatter(x,e,s=s,color='k')
m = np.mean(group)
e = np.std(group)
x = xlocs.pop(0)
o = bar(x,m,width=w,color='0.6',
yerr=e, ecolor='k')

show()


[UPDATE: The answer on StackOverflow was to draw the error bars manually. Call this from the main loop:


def do_error_bar(x,e,lw=3):
w = 3
o = plot([x,x],[m+e,m-e],color='k',lw=lw)
o = plot([x-w,x+w],[m+e,m+e],color='k',lw=lw)
o = plot([x-w,x+w],[m-e,m-e],color='k',lw=lw)


And do this before calling show():
axes().xaxis.set_visible(False)

The new figure: