Posts

Clip 3D array points outside of axes

posted Jul 24, 2012, 6:14 AM by Mart Objartel   [ updated Jul 24, 2012, 6:45 AM ]

Issue:

While plotting a matplotlib 3D plot, if you set axis limits to be lesser than the the maximum range of the array.

The array values are plotted outside the axis area.

Example:

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
from pylab import *

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

X = [-10, 3, 4, 5, 10]
Y = [100, 150, 250, 320, 400]
Z = [12, 23, 33, 44, 52]

ax.plot(X,Y,Z, ls="None", marker="o")

ax.set_xlabel("X")


plt.show()

Now when setting limits for X axis from
-5 to 5, data points outiside the axis are still plotted.
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
from pylab import *


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

X = [-10, 3, 4, 5, 10]
Y = [100, 150, 250, 320, 400]
Z = [12, 23, 33, 44, 52]


ax.plot(X,Y,Z, ls="None", marker="o")

ax.set_xlim3d(-5, 5)
ax.set_xlabel("X")


plt.show()

One possible way to get rid of these data points is to replace them with NaN, for example useing some simple "if logic". NB, for some reason does not work with scatter.

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
from pylab import *


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

X = [-10, 3, 4, 5, 10]
Y = [100, 150, 250, 320, 400]
Z = [12, 23, 33, 44, 52]

for i in np.arange(len(X)):
    if X[i] < -5:
        X[i] = NaN
        Y[i] = NaN
        Z[i] = NaN
    elif X[i] > 5:
        X[i] = NaN
        Y[i] = NaN
        Z[i] = NaN
    else:
        pass


ax.plot(X,Y,Z, ls="None", marker="o")

ax.set_xlim3d(-5, 5)
ax.set_xlabel("X")


plt.show()

Same can be done with wireframes or surfaces. For example one would like to get rid of all the wireframe bellow 0 in Z-axis:
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
from pylab import *

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y, Z = axes3d.get_test_data(0.1)
           
ax.plot_wireframe(X, Y, Z, rstride=2, cstride=2)
           
ax.set_zlim3d(0, 80)
plt.show()

Solution is similar to previous.

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
from pylab import *

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y, Z = axes3d.get_test_data(0.1)

for i in np.arange(len(X)):
    for j in np.arange(len(Y)):
        if Z[j,i] < 0:
            Z[j,i] = NaN
        else:
            pass
           
ax.plot_wireframe(X, Y, Z, rstride=2, cstride=2)
           
ax.set_zlim3d(0, 80)
plt.show()


Animated 3D plot

posted Jul 27, 2011, 3:24 AM by Mart Objartel   [ updated Oct 21, 2011, 1:43 AM ]


import matplotlib.pyplot as plt

import mpl_toolkits.mplot3d.axes3d as axes3d


fig = plt.figure(figsize=(4,4))

ax1 = fig.add_subplot(1, 1, 1, projection='3d')


#data


x = [1,2,3,4,5]

y = [23, 34, 23, 34, 45]

z = [3, 4, 6, 7, 5]


ax1.plot(x,y,z)


for i in range(0, 180):

    ax1.azim = i

#   ax1.elev = 30

    name = "anim_%s.png " % i

    plt.savefig(name, format="png")


#plt.show()


this script will only generate image sequence that can be imported into VirtualDub (http://www.virtualdub.org/), Adobe Flash(R) or some other software to encode it into video/flash/gif




stacked bar plot with legend (hatch pattern), exploded pie chart

posted May 17, 2011, 11:35 PM by Mart Objartel   [ updated Oct 26, 2011, 10:00 AM ]

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(7.4, 7.4))


ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

#data
data_1 = [3, 4, 1, 5, 7]


#pie plot explosion data
expl = [0.1, 0.1, 0.1, 0.1, 0.25]

#calculate the sum of data points
Sum = np.sum(data_1)

#labels data
text_1 = ["proteins", "carbs", "fats", "oils", "minerals"]

#http://matplotlib.sourceforge.net/api/artist_api.html#matplotlib.patches.Patch.set_hatch
def Hatcher(imp):
    if imp == "proteins":
        out = "//"
    elif imp == "carbs":
        out = "--"
    elif imp == "fats":
        out = "xx"
    elif imp == "oils":
        out = "\\"
    else:
        out = "++"

    return out

lefter = 0

#horizontal bar plot
for i in np.arange(0, len(data_1)):
   
    ax1.barh([1], data_1[i],  1,left=lefter, hatch=Hatcher(text_1[i]), color="w", label="%s" % (text_1[i]))
    #add % labels to bars
    ax1.text(lefter+(data_1[i]/2), 1.5, "%s%s" % (data_1[i]*100/Sum, "%"), size=10, backgroundcolor="w")

    lefter += data_1[i]

#hide x ticks   
ax1.set_xticks([])

#asjust y axis
ax1.set_ylim(1,2)

#set y tick location
ax1.set_yticks([1.5])

#replace y tick with text string
ax1.set_yticklabels(["nutrients"])

ax1.set_title("Horizontal bar plot")

#generate legend and move  it off the plot, labels are defined in ax1.barh argument "label="
ax1.legend(bbox_to_anchor = (1.37, 0.8))

#simple pie plot
ax2.pie(data_1, labels=text_1, autopct='%1.0f%%', labeldistance=1.1, explode=expl)
ax2.set_title("Exploded pie plot")


plt.subplots_adjust(right=0.76)
plt.show()


sin, sine, sinus

posted May 9, 2011, 1:37 AM by Mart Objartel

import numpy as np
import matplotlib.pyplot as plt

#http://matplotlib.sourceforge.net/examples/pylab_examples/spine_placement_demo.html

fig = plt.figure(figsize=(4, 5))

ax = fig.add_subplot(111)


x = np.arange(-2*np.pi, 2*np.pi, 0.01)
y = np.sin(x)

ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')

ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

ax.plot(x, y,linewidth="3", alpha=0.3)

ax.plot([0, np.pi/2], [1, 1], ls="--", color="green", linewidth="3",alpha=0.5)
ax.plot([np.pi/2, np.pi/2], [1, 0], ls="--", color="red", linewidth="3",alpha=0.5)

ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')


ax.set_xlim(-2*np.pi, 2*np.pi)

xticker = np.arange(-np.pi-np.pi/2, np.pi+np.pi, np.pi/2)
xlabels = [r"$\frac{-3\pi}{2}$", r"${-\pi}$",r"$\frac{-\pi}{2}$","",r"$\frac{pi}{2}$",r"${\pi}$",r"$\frac{3\pi}{2}$"]

ax.set_xticks(xticker)
ax.set_xticklabels(xlabels, size=17)

ax.text(np.pi, 1.1, "y=sin(x)")

ax.set_ylim(-1.5, 1.5)
yticker = np.arange(-1, 2, 1)
ax.set_yticks(yticker)

plt.show()

3D surface, wireframe, regression

posted May 8, 2011, 11:08 PM by Mart Objartel   [ updated May 9, 2011, 12:32 AM ]

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
import mpl_toolkits.mplot3d.axes3d as axes3d

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

#Data
fx = [0.673574075,0.727952994,0.6746285,0.797313558,0.37664721,0.67939197,0.748490102,0.722048276,0.767189284,0.768296082,0.732383162,0.748429373,0.751570337,0.698977802,0.703398777,0.802607746,0.786242535,0.366661714,0.792490268,0.698636545,0.769904493,0.762656928,0.478595152,0.759151743,0.728607906,0.778099194,0.728575153,0.703794547]
fy = [0.331657721,0.447817839,0.37733386,0.306640864,0.107229109,0.329287287,0.758907052,0.310634309,0.277462605,0.333935925,0.326699919,0.72242944,0.358848707,0.298222369,0.306303486,0.43058538,0.373973649,0.117132288,0.432939444,0.255479494,0.384761779,0.382446444,0.35914706,0.298360515,0.391041147,0.363895412,0.312359532,0.343344197]
fz = [18.13629648,8.620699842,9.807536512,17.40105183,24.44101897,18.81025228,8.075948931,18.10817229,22.24192367,13.8497555,13.28436202,4.472128831,14.53195939,15.93922217,0,0,11.28194885,0,0,26.12423918,9.200498046,14.01392223,14.14545413,17.8320704,8.985897324,10.53443457,12.48561226,11.80438073]

#generate data for regression equation
Xs = np.arange(0.4, 0.8, 0.005)
Ys = np.arange(0.2, 0.7, 0.005)
Xs, Ys = np.meshgrid(Xs, Ys)

#3D regression solved using DataFit(R), http://www.oakdaleengr.com/
Zs = 41.0909875400163+15.3581432751401*np.log(Xs)+-90.9714747515509*Ys+64.9652271333282*Ys**2

ax.plot(fx, fy, fz, linestyle="none", marker="o", mfc="none", markeredgecolor="red")

#plot wireframe
#ax.plot_wireframe(Xs, Ys, Zs, rstride=4, cstride=4, alpha=0.4)

#plot surface, more colormaps: http://matplotlib.sourceforge.net/examples/pylab_examples/show_colormaps.html
ax.plot_surface(Xs, Ys, Zs, rstride=4, cstride=4, alpha=0.4,cmap=cm.jet)

plt.show()

Simple 3d plot with 3d errorbars

posted Apr 25, 2011, 12:17 AM by Mart Objartel   [ updated Apr 25, 2011, 12:20 AM ]

import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as axes3d

fig = plt.figure(dpi=100)
ax = fig.add_subplot(111, projection='3d')



#data
fx = [0.673574075,0.727952994,0.6746285]
fy = [0.331657721,0.447817839,0.37733386]
fz = [18.13629648,8.620699842,9.807536512]

#error data
xerror = [0.041504064,0.02402152,0.059383144]
yerror = [0.015649804,0.12643117,0.068676131]
zerror = [3.677693713,1.345712547,0.724095592]

#plot points
ax.plot(fx, fy, fz, linestyle="None", marker="o")

#plot errorbars
for i in np.arange(0, len(fx)):
    ax.plot([fx[i]+xerror[i], fx[i]-xerror[i]], [fy[i], fy[i]], [fz[i], fz[i]], marker="_")
    ax.plot([fx[i], fx[i]], [fy[i]+yerror[i], fy[i]-yerror[i]], [fz[i], fz[i]], marker="_")
    ax.plot([fx[i], fx[i]], [fy[i], fy[i]], [fz[i]+zerror[i], fz[i]-zerror[i]], marker="_")

#configure axes
ax.set_xlim3d(0.55, 0.8)
ax.set_ylim3d(0.2, 0.5)
ax.set_zlim3d(8, 19)

plt.show()

multible Y axes, parasite axes

posted Apr 21, 2011, 5:37 AM by Mart Objartel   [ updated Apr 21, 2011, 5:39 AM ]


from mpl_toolkits.axes_grid.parasite_axes import SubplotHost
import matplotlib.pyplot as plt
import numpy as np

#data
x = (1, 3, 4, 6, 8, 9, 12)
y1 = (0, 1, 2, 2, 4, 3, 2)
y2 = (0, 3, 2, 3, 6, 4, 5)
y3 = (50, 40, 40, 30, 20, 22, 10)
y4 = (0.2, 0.5, 0.6, 0.9, 2, 5, 2)
y5 = (2, 0.5, 0.9, 9, 12, 15, 12)
y6 = (200, 500, 900, 900, 120, 150, 120)

#credits: http://matplotlib.sourceforge.net/examples/pylab_examples/multiple_yaxis_with_spines.html

class multiY():
    def __init__(self, height, width, X, LY, Xlabel, LYlabel, linecolor,
    set_marker, set_linestyle, fontsize, set_markersize,
    set_linewidth, set_mfc, set_mew, set_mec):
       
        self.X = X
       
        fig = plt.figure(figsize=(height, width))
       
        self.host = SubplotHost(fig, 111)
       

        plt.rc("font", size=fontsize)
       
        self.host.set_xlabel(Xlabel)
        self.host.set_ylabel(LYlabel)
        p1, = self.host.plot(X, LY, color=linecolor, marker=set_marker, ls=set_linestyle, ms=set_markersize, lw=set_linewidth, mfc=set_mfc, mew=set_mew, mec=set_mec)
       
        fig.add_axes(self.host)
       
        self.host.axis["left"].label.set_color(p1.get_color())
        self.host.tick_params(axis='y', color=p1.get_color())
       
    def parasites(self, set_offset, PY, PYlabel, side, Plinecolor,
    Pset_marker, Pset_linestyle, Pset_markersize, Pset_linewidth, Pset_mfc, Pset_mew, Pset_mec):           
        par = self.host.twinx()
        par.axis["right"].set_visible(False)
        offset = (set_offset, 0)
        new_axisline = par.get_grid_helper().new_fixed_axis
       
        par.axis["side"] = new_axisline(loc=side, axes=par, offset=offset)
       
        par.axis["side"].label.set_visible(True)
        par.axis["side"].set_label(PYlabel)
       
        p2, = par.plot(self.X, PY,color=Plinecolor, marker=Pset_marker, ls=Pset_linestyle, ms=Pset_markersize, lw=Pset_linewidth, mfc=Pset_mfc, mew=Pset_mew, mec=Pset_mec)
       
        par.axis["side"].label.set_color(p2.get_color())
        par.tick_params(axis='y', colors=p2.get_color())

#height, width, x-data, y-datam, X-label, Y-label, line color, markerstyle, linestyle,
# fontsize, markersize, linewidth, marker face color, marker edge with, marker edgecolor      
aa = multiY(10, 4, x, y1, "X-label", "Y-label", "r", "o", "None", 16, 8, 2, "none", "1", "r")
#offset, y-data, Y-label, side, color, marker edge with, marker edgecolor
aa.parasites(0, y2, "Parasite2", "right", "g", ">", "--", 10, 1, "none", "1", "g")
aa.parasites(-50, y3, "Parasite3", "left", "b", "<", "-", 10, 1, "none", "1", "b")
aa.parasites(50, y4, "Parasite4", "right", "m", "s", "-.", 10, 1, "none", "1", "m")
aa.parasites(-100, y5, "Parasite5", "left", "y", "d", "none", 10, 1, "none", "1", "y")
aa.parasites(100, y6, "Parasite6", "right", "k", "*", "--", 10, 1, "none", "1", "k")

#adjust the plot
plt.subplots_adjust(left=0.20, bottom=0.15, right=0.78, top=0.92, wspace=0.05, hspace=0)
plt.show()


Scientific notation, text styles, LaTex

posted Apr 21, 2011, 2:57 AM by Mart Objartel



import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(9, 1.5))
ax = fig.add_subplot(111)

x=np.arange(0, 10, 0.1)
y=2*np.tan(x)

ax.set_xlim(0, 10)
ax.set_xticks([1, 2, 3, 4, 5, 6, 7, 8, 9])
#http://matplotlib.sourceforge.net/users/mathtext.html
ax.set_xticklabels([r"$10^{1}$",r"$10^{2}$",r"$10^{3}$",r"$10^{4}$",r"$10^{5}$",r"$10^{6}$",r"$10^{7}$",r"$10^{8}$",r"$10^{9}$" ])

ax.set_ylim(0, 6)
ax.set_yticks([0, 1, 2, 3, 4, 5, 6])
#http://matplotlib.sourceforge.net/users/mathtext.html
ax.set_yticklabels([r"$\Delta$", r"$\Gamma$",r"$\Lambda$",r"$\Omega$",r"$\Phi$",r"$\Pi$",r"$\Psi$"])

ax.text(1, 1, r'$\mathtt{matplotlib}\/{examples}$')
ax.text(2, 2, r'$\mathscr{matplotlib}\/\mathcircled{examples}$', size=25)
ax.bar(x,y, alpha=0.1, color="red")
plt.subplots_adjust(left=0.08, bottom=0.33, right=0.96, top=0.83, wspace=0.05, hspace=0)
plt.show()

3d plot with 3d errorbars, projections, text labels

posted Apr 19, 2011, 1:59 AM by Mart Objartel   [ updated Apr 25, 2011, 12:18 AM ]


import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as axes3d


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')


#data
fname = ["acb","fgj","asd","tert","hjk","aer","cvb","ghj","qwf","hng","cde","iolk","xsa","ong","aasd","ghgh","rtrt","wewe","qwqw","bnbn","jhgd","aghty","dfg","derA","eryh","asdq","Dbgd","SsadI"]
fx = [0.673574075,0.727952994,0.6745,0.793558,0.37664721,0.67939197,0.748490102,0.722048276,0.767189284,0.768296082,0.732383162,0.748429373,0.751570337,0.698977802,0.703398777,0.802607746,0.786242535,0.366661714,0.792490268,0.698636545,0.769904493,0.762656928,0.478595152,0.759151743,0.728607906,0.778099194,0.728575153,0.703794547]
fy = [0.21,0.49,0.36,0.304,0.1009,0.329287287,0.752,0.309,0.277462605,0.333935925,0.326699919,0.72242944,0.358848707,0.298222369,0.03486,0.43058538,0.373973649,0.12288,0.9444,0.2494,0.384761779,0.382446444,0.35914706,0.298360515,0.391041147,0.363895412,0.312359532,0.343344197]
fz = [18,8.620699842,9.2,17.40183,24.44101897,18,8.075948931,19,22.24192367,15,13.28436202,4.472128831,14.53195939,15.93922217,0,0,11.28194885,0,0,26.12423918,9.200498046,14.01392223,14.14545413,17.8320704,8.985897324,10.53443457,12.48561226,11.80438073]

#errorbar data
xSD = [0.041504064,0.02402152,0.059383144,0.038393713,0.054242278,0.018450667,0.083524242,0.042438697,0.036334793,0.023742101,0.041280224,0.003936522,0.025525758,0.031090602,0.027155833,0.038639074,0.061699064,0.11610088,0.075548578,0.059801071,0.069031082,0.071645685,0.050143938,0.049165738,0.020437116,0.046606225,0.039779165,0.019699934]
ySD = [0.015649804,0.12643117,0.068676131,0.016337,0.015050422,0.0651138,0,0.028590823,0.033705502,0.025962039,0,0,0.036646619,0.062000616,0,0,0.026584944,0.005923891,0,0.027485812,0,0.058142106,0.004978857,0.011233057,0.051596586,0.013837766,0,0.054340381]
zSD = [3.677693713,1.345712547,0.724095592,1.856309389,34.56482051,1.487978871,0,1.173906828,2.887602472,0.305603391,0,0,1.791653266,3.842020113,0,0,0.474818671,0,0,5.113750225,0,1.113374167,0.264111881,2.483847286,2.787214029,0.60047479,0,3.881040381]



#Class for 3d object
class thriidii:
    def __init__ (self, azimuut, elevation, x, y, z, d, n, gr, oy, oz, axesS, xl, yl, zl, prj, COL, randinp):
       
       
        self.AZ = azimuut
        self.EL = elevation
   
        self.Dx = x
        self.Dy = y
        self.Dz = z
       
        #get limits
       
        self.maxDx = np.max(self.Dx)
        self.maxDy = np.max(self.Dy)
        self.maxDz = np.max(self.Dz)
       
        self.minDx = np.min(self.Dx)
        self.minDy = np.min(self.Dy)
        self.minDz= np.min(self.Dz)
       
        self.maxXYZ = np.max([np.max(self.Dx), np.max(self.Dy), np.max(self.Dz)])
        self.minXYZ = np.min([np.min(self.Dx), np.min(self.Dy), np.min(self.Dz)])       
       
        self.maxXY = np.max([np.max(self.Dx), np.max(self.Dy)])
        self.minXY = np.min([np.min(self.Dx), np.min(self.Dy)])       
       
        self.maxXZ = np.max([np.max(self.Dx), np.max(self.Dz)])
        self.minXZ = np.min([np.min(self.Dx), np.min(self.Dz)])       
       
        self.maxYZ = np.max([np.max(self.Dy), np.max(self.Dz)])
        self.minYZ = np.min([np.min(self.Dy), np.min(self.Dz)])
       
        print "MAX Dx", self.maxDx
        print "MAX Dy", self.maxDy
        print "MAX Dz", self.maxDz
       
        print "MIN Dx", self.minDx
        print "MIN Dy", self.minDy
        print "MIN Dz", self.minDz
       
       
       
       
       
        for i in  np.arange(0, len(self.Dx)):
           
            #plot data points
            ax.plot([self.Dx[i]], [self.Dy[i]], [self.Dz[i]], ls="None", marker=".", zorder=90, color=COL, mec=COL)
            #plot 3d errorbars
            ax.plot([self.Dx[i]-xSD[i], self.Dx[i]+xSD[i]], [self.Dy[i], self.Dy[i]], [self.Dz[i], self.Dz[i]], alpha=0.3, ls="-", marker="_", zorder=90, color=COL, mec=COL)
            ax.plot([self.Dx[i], self.Dx[i]], [self.Dy[i]-ySD[i], self.Dy[i]+ySD[i]], [self.Dz[i], self.Dz[i]], alpha=0.3, ls="-", marker="_", zorder=90, color=COL, mec=COL)
            ax.plot([self.Dx[i], self.Dx[i]], [self.Dy[i], self.Dy[i]], [self.Dz[i]-zSD[i], self.Dz[i]+zSD[i]], alpha=0.3, ls="-", marker="_", zorder=90, color=COL, mec=COL)
           
           
        #if gr = 1, plot names next to data
        if gr == 1:
            for i in np.arange(0, len(self.Dx)):
                ax.text(self.Dx[i], self.Dy[i]+oy, self.Dz[i]+oz,  "%s" % (n[i]), size=10, color=COL, zorder=100)
              
        else:
            print gr
       

        #function to plot projections (2d plots)   
        def tuudii(arname, asim, elev, axesss):
            for j in set(arname): #iterate trough unique elements in name list
               
                iii = -1
                temp_array = []
                try:
                    while 1:
                       
                        iii = arname.index(j, iii+1) #find all maching indexes for names
                        print "match at", iii, j
                        temp_array.append(iii)
                        #ax.plot([self.Dx[i]], [self.Dy[i]], [self.minDz], ms="x", color="red", zorder=200)
                       
                           
                   
                except ValueError:
                    tmp_2dx = []
                    tmp_2dy = []
                    tmp_2dz = []
                   
                    tmp_2dx_cont = []                 
                    tmp_2dy_cont = []
                    tmp_2dz_cont = []
                   
                    if axesss == 3:
                        minX = self.minXYZ
                        minY = self.minXYZ
                        minZ =self.minXYZ
                        maxX =self.maxXYZ
                        maxY =self.maxXYZ
                        maxZ =self.maxXYZ
                    if axesss == 2:
                        minX = self.minXY
                        minY = self.minXY
                        minZ =self.minDz
                        maxX =self.maxXY
                        maxY =self.maxXY
                        maxZ =self.maxDz               
                    if axesss == 1:
                        minX = self.minXZ
                        minY = self.minDy
                        minZ =self.minXZ
                        maxX =self.maxXZ
                        maxY =self.maxDy
                        maxZ =self.maxXZ
                       
                    if axesss == 0:
                        minX = self.minDx
                        minY = self.minYZ
                        minZ =self.minYZ
                        maxX =self.maxDx
                        maxY =self.maxYZ
                        maxZ =self.maxYZ
                    if axesss == 4:
                        minX = self.minDx
                        minY = self.minDy
                        minZ =self.minDz
                        maxX =self.maxDx
                        maxY =self.maxDy
                        maxZ =self.maxDz
                    else:
                        pass
                       
                    for i in temp_array:
                   
                        tmp_2dx.append(self.Dx[i])
                        tmp_2dy.append(self.Dy[i])
                        tmp_2dz.append(self.Dz[i])
                        #depending of plotting angle choose where to plot projections
                        if asim < 90:
                            tmp_2dx_cont.append(minX)
                            x_cont = minX
                            tmp_2dy_cont.append(minY)
                            y_cont = minY
                        else:
                            tmp_2dx_cont.append(maxX)
                            x_cont = maxX
                            tmp_2dy_cont.append(minY)
                            y_cont = minY
                       
                        if elev > 0:
                            tmp_2dz_cont.append(minZ)
                            z_cont = minZ
                        else:
                            tmp_2dz_cont.append(maxZ)
                            z_cont = maxZ

                       
                    ax.plot(tmp_2dx, tmp_2dy, tmp_2dz_cont, ls="dotted", color="#C0C0C0")
                   
                   
                    ax.plot(tmp_2dx, tmp_2dy_cont, tmp_2dz, ls="dotted", color="#C0C0C0")
                   
                   
                    ax.plot(tmp_2dx_cont, tmp_2dy, tmp_2dz, ls="dotted", color="#C0C0C0")
                   
                   
                   
                    for k in temp_array:
                        print "K:", k
                        ax.plot([x[k]], [y[k]], [z_cont], marker=".", color="#C0C0C0")
                       
                        ax.plot([x[k]-xSD[k], x[k]+xSD[k]], [y[k], y[k]], [z_cont, z_cont], alpha=0.3,marker="_", color="#C0C0C0")
                        ax.plot([x[k], x[k]], [y[k]-ySD[k], y[k]+ySD[k]], [z_cont, z_cont], alpha=0.3,marker="_", color="#C0C0C0")
                       
                       
                       
                       
                        ax.plot([x[k]], [y_cont], [z[k]], marker=".", color="#C0C0C0")
                        ax.plot([x[k]-xSD[k], x[k]+xSD[k]], [y_cont, y_cont], [z[k], z[k]], marker="_", color="#C0C0C0")
                        ax.plot([x[k], x[k]], [y_cont, y_cont], [z[k]-zSD[k], z[k]+zSD[k]], marker="_", color="#C0C0C0")
                       
                                        
                       
                        ax.plot([x_cont], [y[k]], [z[k]], marker=".", color="#C0C0C0")
                       
                        ax.plot([x_cont, x_cont], [y[k]-ySD[k], y[k]+ySD[k]], [z[k], z[k]], marker="_", color="#C0C0C0")
                        ax.plot([x_cont, x_cont], [y[k], y[k]], [z[k]-zSD[k], z[k]+zSD[k]], marker="_", color="#C0C0C0")
                       
                       
                       
                        ax.text(self.Dx[k], self.Dy[k]+0.01, z_cont+0.5,  "%s" % (n[k]), size=9, zorder=1, color="#C0C0C0")
                        ax.text(self.Dx[k], y_cont+0.01, self.Dz[k]+0.5,  "%s" % (n[k]), size=9, zorder=1, color="#C0C0C0")
                        ax.text(x_cont, self.Dy[k]+0.01, self.Dz[k]+0.5,  "%s" % (n[k]), size=9, zorder=1, color="#C0C0C0")
                       
                       
                       
       
        ax.set_xlabel(xl)
        ax.set_ylabel(yl)
        ax.set_zlabel(zl)
       
        #uncomment next 2 lines to draw a viewing angle information on the plot
       
        #TITLE = "az: %s, el: %s" % (self.AZ, self.EL)
        #plt.title(TITLE)
           
        ax.azim = self.AZ
        ax.elev = self.EL
       


           
           
        if prj == 1:
            tuudii(n, self.AZ, self.EL, axesS)
           
           
        else:
            pass
       
       
        if axesS == 4:
            ax.set_xlim3d(self.minDx,self.maxDx)
            ax.set_ylim3d(self.minDy,self.maxDy)
            ax.set_zlim3d(self.minDz,self.maxDz)
            print "XYZ min:",self.minXYZ,"XYZ max:",self.maxXYZ
        if axesS == 3:
            ax.set_xlim3d(self.minXYZ,self.maxXYZ)
            ax.set_ylim3d(self.minXYZ,self.maxXYZ)
            ax.set_zlim3d(self.minXYZ,self.maxXYZ)
            print "XYZ min:",self.minXYZ,"XYZ max:",self.maxXYZ
        if axesS == 2:
            ax.set_xlim3d(self.minXY,self.maxXY)
            ax.set_ylim3d(self.minXY,self.maxXY)
            ax.set_zlim3d(self.minDz,self.maxDz)
            print "XY min:",self.minXYZ,"XY max:",self.maxXYZ, "Z min:", self.minDz,"Z max:", self.maxDz       
        if axesS == 1:
            ax.set_xlim3d(self.minXZ,self.maxXZ)
            ax.set_ylim3d(self.minDy,self.maxDy)
            ax.set_zlim3d(self.minXZ,self.maxXZ)
            print "XZ min:",self.minXZ,"XZmax:",self.maxXZ, "Y min:", self.minDy,"Y max:", self.maxDy
        if axesS == 0:
            ax.set_xlim3d(self.minDx,self.maxDx)
            ax.set_ylim3d(self.minYZ,self.maxYZ)
            ax.set_zlim3d(self.minYZ,self.maxYZ)
            print "YZ min:",self.minYZ,"YZmax:",self.maxYZ, "X min:", self.minDx,"X max:", self.maxDx
        else:
            pass
        #plt.savefig("%s.png" % (randinp), format="png")
        plt.show()
       
# azimuut, elevation, x, y, z, ,name_list, gr, norm, Ylabeloffset, Zlabeloffset, xlabel, ylabel, zlabel, projections, color, random number)

#with projections
#thriidii(45, 22, fx, fy, fz, fz, fname, 1,0.01, 0.5, 4, "speed", "might", "fame", 1, "green",1)

#without projections
thriidii(45, 22, fx, fy, fz, fz, fname, 1,0.01, 0.5, 4, "speed", "might", "fame", 0, "green",1)



3x6 2D plots, with normalized data and special characters(LaTeX) in labels

posted Apr 19, 2011, 1:23 AM by Mart Objartel   [ updated Apr 21, 2011, 3:07 AM ]

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as co

#data
out1 = [11,13,14,15,17,21,21,27]
out2 = [1236,1673,2203,2803,3288,3610,3675,4132]
out3 = [492,626,731,850,865,817,659,550]
out4 = [68,205,325,421,611,883,1343,1646]
out5 = [1612,2274,2894,3643,4206,4287,4934,5475]
out6 = [1346,1833,2383,3576,2919,3306,3517,3364]
out7 = [1252,1634,2149,2761,3071,3205,3088,3278]
out8 = [13595,18271,23755,29429,33968,36602,36706,39761]
out9 = [6341,9619,17873,15622,23714,18384,20295,21127]
out10 = [84,112.6,248.3936402,420.9011487,632,825,971.27,1343.7]
out11 = [374,535.1847201,821.9746154,1147.672,1526.072807,1857.583225,2165.713401,2712.648204]
I_out1 = [1305,1991.881,2671.393,3394.5,4093.24719,4706.72,5243.552,6016.643]
gas1 = [4186,7473,10356,11242,11475,12149,12149,12149]
gas2 = [0,0,0,7,62,601,342,396,]
gas3 = [3,7,7.8,13,16,19,20,23]
flux1 = [0,0,0,1.5001,10.35221696,12.4,25.934,33.727]
flux2 = [6,13.69,22.358,31.7604005,42.0262,47.8298,56.31445151,72.54693]
flux3 = [17,20.048,27.779,31.7394,31.211,29.0254371,23.9779,29.64697]
flux4 = [98,75,91,18,64,88,33,48]

#function to normalize data(right y axis)
def norm(y):
    normf = co.normalize()
    normr = normf(y)
    return normr


#define figure and figure size figsize=(width, height)
fig = plt.figure(figsize=(6.299, 9))

#define subplots 3x6
# 1        2    3
# 4        5    6
# 7        8    9
# 10    11    12
# 13    14    15
# 16    17    18


ax1 = fig.add_subplot(6,3,1) #gas1
ax1n = fig.add_subplot(6,3,1, sharex=ax1, frameon=False) #gas1 nomeeritud


ax2 = fig.add_subplot(6,3,2) #out9
ax2n = fig.add_subplot(6,3,2, sharex=ax2, frameon=False) #out9

ax3 = fig.add_subplot(6,3,3) #out8
ax3n = fig.add_subplot(6,3,3, sharex=ax3, frameon=False) #out8


ax4 = fig.add_subplot(6,3,4) #out2
ax4n = fig.add_subplot(6,3,4, sharex=ax4, frameon=False) #out2

ax5 = fig.add_subplot(6,3,5) #out5
ax5n = fig.add_subplot(6,3,5, sharex=ax5, frameon=False) #out5


ax6 = fig.add_subplot(6,3,6) #I_out1
ax6n = fig.add_subplot(6,3,6, sharex=ax6, frameon=False) #I_out1


ax7 = fig.add_subplot(6,3,7) #out11
ax7n = fig.add_subplot(6,3,7, sharex=ax7, frameon=False) #out11

ax8 = fig.add_subplot(6,3,8) #out7
ax8n = fig.add_subplot(6,3,8,sharex=ax8, frameon=False) #out7


ax9 = fig.add_subplot(6,3,9) #out6
ax9n = fig.add_subplot(6,3,9, sharex=ax9, frameon=False) #out6


ax10 = fig.add_subplot(6,3,10) #out3
ax10n = fig.add_subplot(6,3,10, sharex=ax10, frameon=False) #out3


ax11 = fig.add_subplot(6,3,11) #out10
ax11n = fig.add_subplot(6,3,11, sharex=ax11, frameon=False) #out10


ax12 = fig.add_subplot(6,3,12) #out4
ax12n = fig.add_subplot(6,3,12, sharex=ax12, frameon=False) #out4

ax13 = fig.add_subplot(6,3,13) #flux2
ax13n = fig.add_subplot(6,3,13, sharex=ax13, frameon=False) #flux2


ax14 = fig.add_subplot(6,3,14) #flux4
ax14n = fig.add_subplot(6,3,14, sharex=ax14, frameon=False) #flux4

ax15 = fig.add_subplot(6,3,15) #gas2
ax15n = fig.add_subplot(6,3,15, sharex=ax15, frameon=False) #gas2



ax16 = fig.add_subplot(6,3,16) #gas3
ax16n = fig.add_subplot(6,3,16, sharex=ax16, frameon=False) #gas3

ax17 = fig.add_subplot(6,3,17) #flux1
ax17n = fig.add_subplot(6,3,17, sharex=ax17, frameon=False) #flux1


ax18 = fig.add_subplot(6,3,18) #flux3
ax18n = fig.add_subplot(6,3,18, sharex=ax18, frameon=False) #flux3

#plot data and normalized data
ax1.plot(out1, gas1, ls="None", marker="o",mfc="None", color="k")
ax1n.plot(out1, norm(gas1), ls="dotted",  color="k")

ax2.plot(out1, out9, ls="None", marker="s", mfc="None",color="k")
ax2n.plot(out1, norm(out9), ls="dotted",color="k")

ax3.plot(out1, out8, ls="None", marker="d",mfc="None", color="k")
ax3n.plot(out1, norm(out8), ls="dotted",mfc="None", color="k")

ax4.plot(out1, I_out1, ls="None", marker="+", color="k")
ax4n.plot(out1, norm(I_out1), ls="dotted", color="k")

ax5.plot(out1, out5, ls="None", marker="s", color="k")
ax5n.plot(out1, norm(out5), ls="dotted", color="k")


ax6.plot(out1, out2, ls="None", marker="x", color="k")
ax6n.plot(out1, norm(out2), ls="dotted", color="k")

ax7.plot(out1, out11, ls="None", marker=">", color="k")
ax7n.plot(out1, norm(out11), ls="dotted",  color="k")

ax8.plot(out1, out7, ls="None", marker="<", color="k")
ax8n.plot(out1, norm(out7), ls="dotted",  color="k")


ax9.plot(out1, out6, ls="None", marker="^", color="k")
ax9n.plot(out1, norm(out6), ls="dotted", color="k")

ax10.plot(out1, out3, ls="None", marker=">",mfc="None", color="k")
ax10n.plot(out1, norm(out3), ls="dotted",mfc="None", color="k")

ax11.plot(out1, out10, ls="None", marker="<",mfc="None", color="k")
ax11n.plot(out1, norm(out10), ls="dotted", marker="<",mfc="None", color="k")

ax12.plot(out1, out4, ls="None", marker="^",mfc="None", color="k")
ax12n.plot(out1, norm(out4), ls="dotted", mfc="None", color="k")

ax13.plot(out1, flux2, ls="None", marker="o", color="k")
ax13n.plot(out1, norm(flux2), ls="dotted",  color="k")

ax14.plot(out1, flux4, ls="None", marker="d", color="k")
ax14n.plot(out1, norm(flux4), ls="dotted",  color="k")

ax15.plot(out1, gas2, ls="None", marker="*", color="k")
ax15n.plot(out1, norm(gas2), ls="dotted",  color="k")

ax16.plot(out1, gas3, ls="None", marker="_", color="k")
ax16n.plot(out1, norm(gas3), ls="dotted", color="k")

ax17.plot(out1, flux1, ls="None", marker="v", color="k")
ax17n.plot(out1, norm(flux1), ls="dotted", color="k")

ax18.plot(out1, flux3, ls="None", marker="v",mfc="None", color="k")
ax18n.plot(out1, norm(flux3), ls="dotted", mfc="None", color="k")



#configure axis

#123
ax1.set_ylim(3000, 50000)
ax2.set_ylim(3000, 50000)
ax3.set_ylim(3000, 50000)

ax1.set_yticks(np.arange(5000, 50000, 10000))
ax2.set_yticks(np.arange(5000, 50000, 10000))
ax3.set_yticks(np.arange(5000, 50000, 10000))

#hide Y tick labels for some plots(only plots on the left and right have labels and ticklabels
ax2.set_yticklabels([])
ax3.set_yticklabels([])

ax1.set_xlim(5, 35)
ax2.set_xlim(5, 35)
ax3.set_xlim(5, 35)

ax1.set_xticks(np.arange(10, 35, 5))
ax2.set_xticks(np.arange(10, 35, 5))
ax3.set_xticks(np.arange(10, 35, 5))



ax2.set_xticklabels([])
ax3.set_xticklabels([])

#456
ax4.set_ylim(500, 7500)
ax5.set_ylim(500, 7500)
ax6.set_ylim(500, 7500)

ax4.set_yticks(np.arange(1000, 8000, 1500))
ax5.set_yticks(np.arange(1000, 8000, 1500))
ax6.set_yticks(np.arange(1000, 8000, 1500))


ax5.set_yticklabels([])
ax6.set_yticklabels([])

ax4.set_xlim(5, 35)
ax5.set_xlim(5, 35)
ax6.set_xlim(5, 35)

ax4.set_xticks(np.arange(10, 35, 5))
ax5.set_xticks(np.arange(10, 35, 5))
ax6.set_xticks(np.arange(10, 35, 5))

ax4.set_xticklabels([])
ax5.set_xticklabels([])
ax6.set_xticklabels([])

#789
ax7.set_ylim(0, 4000)
ax8.set_ylim(0, 4000)
ax9.set_ylim(0, 4000)

ax7.set_yticks(np.arange(500, 4000, 1000))
ax8.set_yticks(np.arange(500, 4000, 1000))
ax9.set_yticks(np.arange(500, 4000, 1000))

ax8.set_yticklabels([])
ax9.set_yticklabels([])

ax7.set_xlim(5, 35)
ax8.set_xlim(5, 35)
ax9.set_xlim(5, 35)

ax7.set_xticks(np.arange(10, 35, 5))
ax8.set_xticks(np.arange(10, 35, 5))
ax9.set_xticks(np.arange(10, 35, 5))

ax7.set_xticklabels([])
ax8.set_xticklabels([])
ax9.set_xticklabels([])

# 10, 11, 12
ax10.set_ylim(-100, 2000)
ax11.set_ylim(-100, 2000)
ax12.set_ylim(-100, 2000)

ax10.set_yticks(np.arange(0, 1900, 300))
ax11.set_yticks(np.arange(0, 1900, 300))
ax12.set_yticks(np.arange(0, 1900, 300))

ax11.set_yticklabels([])
ax12.set_yticklabels([])

ax10.set_xlim(5, 35)
ax11.set_xlim(5, 35)
ax12.set_xlim(5, 35)

ax10.set_xticks(np.arange(10, 35, 5))
ax11.set_xticks(np.arange(10, 35, 5))
ax12.set_xticks(np.arange(10, 35, 5))

ax10.set_xticklabels([])
ax11.set_xticklabels([])
ax12.set_xticklabels([])

# 13, 14, 15
ax13.set_ylim(-50, 700)
ax14.set_ylim(-50, 700)
ax15.set_ylim(-50, 700)

ax13.set_yticks(np.arange(0, 750, 150))
ax14.set_yticks(np.arange(0, 750, 150))
ax15.set_yticks(np.arange(0, 750, 150))

ax14.set_yticklabels([])
ax15.set_yticklabels([])

ax13.set_xlim(5, 35)
ax14.set_xlim(5, 35)
ax15.set_xlim(5, 35)

ax13.set_xticks(np.arange(10, 35, 5))
ax14.set_xticks(np.arange(10, 35, 5))
ax15.set_xticks(np.arange(10, 35, 5))

ax13.set_xticklabels([])
ax14.set_xticklabels([])
ax15.set_xticklabels([])

# 16, 17, 18
ax16.set_ylim(-5, 45)
ax17.set_ylim(-5, 45)
ax18.set_ylim(-5, 45)

ax16.set_yticks(np.arange(0, 50, 10))
ax17.set_yticks(np.arange(0, 50, 10))
ax18.set_yticks(np.arange(0, 50, 10))

ax17.set_yticklabels([])
ax18.set_yticklabels([])

ax16.set_xlim(5, 35)
ax17.set_xlim(5, 35)
ax18.set_xlim(5, 35)

ax16.set_xticks(np.arange(10, 35, 5))
ax17.set_xticks(np.arange(10, 35, 5))
ax18.set_xticks(np.arange(10, 35, 5))



#disable labels for some plots
ax1n.set_yticklabels([])
ax2n.set_yticklabels([])

ax4n.set_yticklabels([])
ax5n.set_yticklabels([])

ax7n.set_yticklabels([])
ax8n.set_yticklabels([])

ax10n.set_yticklabels([])
ax11n.set_yticklabels([])

ax13n.set_yticklabels([])
ax14n.set_yticklabels([])

ax16n.set_yticklabels([])
ax17n.set_yticklabels([])


#define the location of ticks

ax1n.yaxis.tick_right()
ax2n.yaxis.tick_right()
ax3n.yaxis.tick_right()
ax4n.yaxis.tick_right()
ax5n.yaxis.tick_right()
ax6n.yaxis.tick_right()
ax7n.yaxis.tick_right()
ax8n.yaxis.tick_right()
ax9n.yaxis.tick_right()
ax10n.yaxis.tick_right()
ax11n.yaxis.tick_right()
ax12n.yaxis.tick_right()
ax13n.yaxis.tick_right()
ax14n.yaxis.tick_right()
ax15n.yaxis.tick_right()
ax16n.yaxis.tick_right()
ax17n.yaxis.tick_right()
ax18n.yaxis.tick_right()

ax1.yaxis.tick_left()
ax2.yaxis.tick_left()
ax3.yaxis.tick_left()
ax4.yaxis.tick_left()
ax5.yaxis.tick_left()
ax6.yaxis.tick_left()
ax7.yaxis.tick_left()
ax8.yaxis.tick_left()
ax9.yaxis.tick_left()
ax10.yaxis.tick_left()
ax11.yaxis.tick_left()
ax12.yaxis.tick_left()
ax13.yaxis.tick_left()
ax14.yaxis.tick_left()
ax15.yaxis.tick_left()
ax16.yaxis.tick_left()
ax17.yaxis.tick_left()
ax18.yaxis.tick_left()


ax1n.set_ylim(-0.1,1.1)
ax2n.set_ylim(-0.1,1.1)
ax3n.set_ylim(-0.1,1.1)
ax4n.set_ylim(-0.1,1.1)
ax5n.set_ylim(-0.1,1.1)
ax6n.set_ylim(-0.1,1.1)
ax7n.set_ylim(-0.1,1.1)
ax8n.set_ylim(-0.1,1.1)
ax9n.set_ylim(-0.1,1.1)
ax10n.set_ylim(-0.1,1.1)
ax11n.set_ylim(-0.1,1.1)
ax12n.set_ylim(-0.1,1.1)
ax13n.set_ylim(-0.1,1.1)
ax14n.set_ylim(-0.1,1.1)
ax15n.set_ylim(-0.1,1.1)
ax16n.set_ylim(-0.1,1.1)
ax17n.set_ylim(-0.1,1.1)
ax18n.set_ylim(-0.1,1.1)


ax3n.yaxis.set_label_position("right")
ax6n.yaxis.set_label_position("right")
ax9n.yaxis.set_label_position("right")
ax12n.yaxis.set_label_position("right")
ax15.yaxis.set_label_position("right")
ax18.yaxis.set_label_position("right")


#enable grid lines

ax1.grid(True)
ax2.grid(True)
ax3.grid(True)
ax4.grid(True)
ax5.grid(True)
ax6.grid(True)
ax7.grid(True)
ax8.grid(True)
ax9.grid(True)
ax10.grid(True)
ax11.grid(True)
ax12.grid(True)
ax13.grid(True)
ax14.grid(True)
ax15.grid(True)
ax16.grid(True)
ax17.grid(True)
ax18.grid(True)



#set Y labels
ax1.set_ylabel(r"$\mu{g}\/ (h)^{-1}$")
ax4.set_ylabel(r"$\mu{g}\/ (h)^{-1}$")
ax7.set_ylabel(r"$\mu{g}\/ (h)^{-1}$")
ax10.set_ylabel(r"$\mu{g}\/ (h)^{-1}$")
ax13.set_ylabel(r"$\mu{g}\/ (h)^{-1}$")
ax16.set_ylabel(r"$\mu{g}\/(h)^{-1}$")
#set X labels
ax16.set_xlabel(r"$\mu{mol}\/ {L}^{-1}$")
ax17.set_xlabel(r"$\mu{mol}\/ {L}^{-1}$")
ax18.set_xlabel(r"$\mu{mol}\/{L}^{-1}$")

#adjust plot spacing
plt.subplots_adjust(left=0.15, bottom=0.06, right=0.93, top=0.97, wspace=0.05, hspace=0)

#finally draw the plot
plt.show()

1-10 of 12