Search code examples
pythonmatplotlibsubplot

Subplot not working properly


Here is the code I have written to generate a 2 by 2 subplot.

The code is presented below:

import math
import numpy
import functools
import operator
from fractions import Fraction
import matplotlib.pyplot as plt
import pylab
from pylab import *


def nCk(n, k):
    return int(functools.reduce(operator.mul,
                                (Fraction(n-i, i+1) for i in range(k)), 1))

Theta = 0.5 cList = numpy.arange(-5, 5, 1) NList = [5, 10, 100, 1000]

for i in list(range(len(NList))):
    N = NList[i]
    print(N)
    dList = []

    for c in cList:
        print(c)
        var = math.floor(float(N*Theta) + float(c*Theta*(1-Theta)*math.sqrt(N)))
        dList.append(pow(0.5, N)*(sum(nCk(N, x) for x in range(var))))

    print([1+math.floor(i/2), 1+i % 2])

    # plt.subplot(4,1+math.floor(i/2),1+i%2)
    # plt.plot(cList,dList)
    # plt.title([1+math.floor(i/2),1+i%2])

    subplot(4, 1+math.floor(i/2), 1+i % 2)
    fig = plot(cList, dList)


# plt.savefig('C:/Users/Sumit_G/foo1.png')
pylab.savefig('C:/Users/Sumit_G/foo.png')

However, instead of getting a 2 by 2 plot.

I am getting the figure produced below:

enter image description here


Solution

  • You are unnecessarily flooring and mod-ing your values. Subplot takes 3 arguments subplot(nrows, ncols, plot_number) (http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplot), where the plot_number is the active plot starting from 1 (top left) and finishing at nrows*ncols (bottom right). See attached graphs.

    enter image description here