some_programmer
some_programmer

Reputation: 3568

How to neaten up this code into a more Pythonic way?

I have plotted a box and whiskers plot for my data using the following code:

def make_labels(ax, boxplot):
    iqr = boxplot['boxes'][0]
    caps = boxplot['caps']
    med = boxplot['medians'][0]
    fly = boxplot['fliers'][0]
    xpos = med.get_xdata()
    xoff = 0.1 * (xpos[1] - xpos[0])
    xlabel = xpos[1] + xoff
    median = med.get_ydata()[1]
    pc25 = iqr.get_ydata().min()
    pc75 = iqr.get_ydata().max()
    capbottom = caps[0].get_ydata()[0]
    captop = caps[1].get_ydata()[0]
    ax.text(xlabel, median, 'Median = {:6.3g}'.format(median), va='center')
    ax.text(xlabel, pc25, '25th percentile = {:6.3g}'.format(pc25), va='center')
    ax.text(xlabel, pc75, '75th percentile = {:6.3g}'.format(pc75), va='center')
    ax.text(xlabel, capbottom, 'Bottom cap = {:6.3g}'.format(capbottom), va='center')
    ax.text(xlabel, captop, 'Top cap = {:6.3g}'.format(captop), va='center')
    for flier in fly.get_ydata():
        ax.text(1 + xoff, flier, 'Flier = {:6.3g}'.format(flier), va='center')  

and this gives me the following graph: enter image description here

Now, what I want to do is to grab all the 'Flier' points that we can see in the graph and make it into a list and for that I did the following:

fliers_data = []    
def boxplots(boxplot):
    iqr = boxplot['boxes'][0]
    fly = boxplot['fliers'][0]
    pc25 = iqr.get_ydata().min()
    pc75 = iqr.get_ydata().max()
    inter_quart_range = pc75 - pc25
    max_q3 = pc75 + 1.5*inter_quart_range
    min_q1 = pc25 - 1.5*inter_quart_range   
    for flier in fly.get_ydata():
        if (flier > max_q3):
            fliers_data.append(flier)
        elif (flier < min_q1):
            fliers_data.append(flier)

Now, I have 2 queries:

  1. In both functions, there are a few lines that are similar. Is there a way I can define them once and use them in both the functions?
  2. Can the second function be edited or neatened in a more efficient way?

Upvotes: 0

Views: 65

Answers (1)

Alfie Atkinson
Alfie Atkinson

Reputation: 58

I think mostly its quite neat, the only thing I can suggest is spaces between different parts of the functions and maybe some quotes to tell someone reading what each part does?

Something like this, for example:

def myfunction(x):

# checking if x equals 10
    if x == 10:
        return True

# if equals 0 return string
    elif x == 0:
        return "equals zero"

# else return false
    else:
        return False

Also, I think you can locate any variables that are the same outside and before both functions (say, at the very start of your code) they should still be accessible in the functions.

Upvotes: 1

Related Questions