Unable to make sequential calls to functions with create matplotlib graphs ... second gets jumbled

Eric,

thanks for follow-up! No, I didn't miss it. Saw it Sunday night my time and spent time with my son getting him ready for start of university istead.

Re the setup of Python ... I will do that this week.

Here's the code extract:

#!/usr/bin/env python
# −*− coding: UTF−8 −*−

import matplotlib
matplotlib.use('Agg') # before importing pyplot per docs
import matplotlib.pyplot as plt
import numpy as np

[snipped the import of Python and Django libraries]

···

###########################################################
def CreateAllWebSite():
    # whichever of these is called first is done fine. Second flawed. calling one at at time, each works ok
    CreateMemberStatCategoryFigure()
    CreateMemberStatFigure()
###############################################
def CreateMemberStatFigure():
    """
    This function creates the member statistics bar chart that is published multiple locations.
    """
    membertypes=Membertype.objects.filter(active=True).order_by('emailorder').exclude(typecode='EXEC')
    mtypes=[]
    barchartcolor=[]
    mtypecodes=[]
    for i in membertypes:
        mtypecodes.append(i.typecode)
        mtypes.append(i.description)
        barchartcolor.append(i.barchartcolor)
    memberstatsm=MemberStatistics.monthly_objects.all()
    memberstatsp=MemberStatistics.monthlypivotbytype_objects.all()
    for i in memberstatsm:
        monthend=i['Date']

##### this section in development. a more generic way; but can't get the calls to p=plt to work.
##### proably needs version 1.0 of Matplotlib or something. As it works, optimise and fix later.
# print mtypes,mtypecodes,barchartcolor
# width=24
# month=[]
# for j in memberstatsp:
# month.append(None2Zero(j['month']))
# N=len(month)
# base=np.zeros(N,int) # start off the base with zeros
# for i in membertypes:
# array1=[]
# for j in memberstatsp:
# array1.append(None2Zero(j[i.typecode]))
# array1=np.array(array1)
# p=plt.bar(month,array1,width,bottom=base,linewidth=0)
# base=base+array1
# plt.yticks(np.arange(0,200,20))
# plt.title(ORG_NAME+' Membership by Month')
# plt.ylabel('Count')
# plt.show()
# return
    
#####
        
    corp1=[]
    corp2=[]
    corp3=[]
    ordm=[]
    ordr=[]
    ordh=[]
    month=[]
    for i in memberstatsp:
        month.append(None2Zero(i['month']))
        corp1.append(None2Zero(i['CORP1']))
        corp2.append(None2Zero(i['CORP2']))
        corp3.append(None2Zero(i['CORP3']))
        ordm.append(None2Zero(i['ORM']))
        ordr.append(None2Zero(i['ORMR']))
        ordh.append(None2Zero(i['HON']))
    N=len(month)
    corp1=np.array(corp1)
    corp2=np.array(corp2)
    corp3=np.array(corp3)
    ordm=np.array(ordm)
    ordr=np.array(ordr)
    ordh=np.array(ordh)

    base=np.zeros(N,int)
    base1=base+ordh
    base2=base1+corp3
    base3=base2+corp2
    base4=base3+corp1
    base5=base4+ordm
    
    width = 24 # the width of the bars: can also be len(x) sequence
    
    p1 = plt.bar(month, ordh, width, color=barchartcolor[0],linewidth=0)
    p2 = plt.bar(month, corp3, width, color=barchartcolor[1],bottom=base1,linewidth=0)
    p3 = plt.bar(month, corp2, width, color=barchartcolor[2],bottom=base2,linewidth=0)
    p4 = plt.bar(month, corp1, width, color=barchartcolor[3],bottom=base3,linewidth=0)
    p5 = plt.bar(month, ordm, width, color=barchartcolor[4],bottom=base4,linewidth=0)
    p6 = plt.bar(month, ordr, width, color=barchartcolor[5],bottom=base5,linewidth=0)

    plt.yticks(np.arange(0,200,20))
    plt.title(ORG_NAME+' Membership by Month')
    plt.ylabel('Count')
    plt.legend( (p1[0], p2[0], p3[0], p4[0], p5[0], p6[0]),mtypes,loc='best')
    plt.show()
    
    matplotlib.rcParams['figure.figsize']=(3,2)
    
    fn=TEMP_DIR+SOC_MEMBER_STAT_BARCHART_FIGURE
    print " CreateMemberStatFigure(): Saving ",fn,"..."
    plt.savefig(fn)
    
    return

###############################################
def CreateMemberStatCategoryFigure():
    """
    This function creates the member statistics category bar chart that is published multiple locations.
    """
    dt=strftime("%d %B %Y", gmtime())
    membercategories=Membercategory.objects.all()
    mcats=[]
    cnt=[]
    for i in membercategories:
        mcats.append(i.category)
        cnt.append(Member.Active_objects.filter(membercategory__category=i.category).count())
    xlocations = np.array(range(len(mcats)))+0.5
    
    print mcats
    print cnt
    p1 = plt.bar(xlocations,cnt)
    plt.figtext(0.15,0.85,dt)
    plt.xticks(xlocations+0.4, mcats,rotation=17)
    plt.title(ORG_NAME+' Membership by Member Category')
    plt.ylabel('Count')
    plt.show()
    
    matplotlib.rcParams['figure.figsize']=(3,2)
    
    fn=TEMP_DIR+SOC_MEMBER_STAT_BARCHART_CAT_FIGURE
    print " CreateMemberStatCategoryFigure(): Saving ",fn,"..."
    plt.savefig(fn)
    print " CreateMemberStatCategoryFigure(): ",SOC_MEMBER_STAT_BARCHART_CAT_FIGURE," created ..."
    
    return

################################################

On 9 Aug 2010, at 07:41, Eric Firing wrote:

Did you miss my reply to the list?

Eric

-------- Original Message --------
Subject: Re: [Matplotlib-users] Unable to make sequential calls to functions with create matplotlib graphs ... second gets jumbled
Date: Sun, 08 Aug 2010 08:10:37 -1000
From: Eric Firing <efiring@...202...>
Organization: University of Hawaii
To: matplotlib-users@lists.sourceforge.net

On 08/08/2010 12:53 AM, Rob Schneider wrote:

Running 0.98.5.3
(would upgrade to 1.0 but having trouble installing it on Mac OS X as it doesn't appear to like the version of Python Apple provides).

Standard procedure on the Mac is to install the python from python.org.
That way you don't risk fouling up the python that OS X is depending on,
and at the same time your own code can use the version of python that
most extension packages are built for.

I have a module where there are two functions which call matplotlib to each create a different graph which both saved to an output PNG file. The import statements:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np

are at the top of the module file. Neither function imports anything specifically, relying on the above imports.

I call each function sequentially. The result is that the first graph is created correctly. The second graph is flawed, and in fact shows the legend from the first function. When I reverse the function calls, which ever graphing function is called first is ok, but second is flawed. If I call each function on it's own, within the same Python session, the graphs (both) get produced flawlessly.

both charts are bar charts; but one does a stacked bar and the other is a simple bar chart.

Why would I not be able to call the two functions sequentially? Why does the first call interfere with the second call?

I don't think anyone is going to be able to answer this question until
you provide a minimal stand-alone code example. Also, the process of
stripping your code down to the shortest example that displays the
undesired behavior may show you where the problem lies.

Eric