Search code examples
pythonmatplotlibgraphing

Matplotlib; Help setting ylimit in subplot


I searched and couldn't find what I was looking for.

How can I set the y limit range on the y axis of a subplot? Below is a demo of what I'm trying to accomplish. Right now the ranges are automatic. I want to set a specific y limit range on the first subplot from say 50 to 100. I tried a few things with no luck (you will see it commented out).

import math
import matplotlib.pyplot as plt
import random


def graphIt(tupleList1, title1, List2, title2, List3, title3):
    x = []
    y = []
    x2 = []
    y2 = []
    x3 = []
    y3 = []
    for i in range(len(tupleList1)):
        x.append(tupleList1[i][0])
        y.append(tupleList1[i][1])
    for i in range(len(List2)):
        x2.append(List2[i])
        y2.append(1)
    for i in range(len(List3)):
        x3.append(List3[i])
        y3.append(1)
    f, plotarray = plt.subplots(3, sharex=True)
    #plt.ylim((50, 100)) #<--This sets the range of plotarray[2]
    #plotarray[0].ylim((50,100)) #<---No such attribute 'ylim'
    plotarray[0].plot(x,y,"o-")
    plotarray[0].set_title(title1)
    plotarray[1].bar(x2,y2,0.15,color='b',label=title2)
    plotarray[1].set_title(title2)
    plotarray[2].bar(x3,y3,0.15,color='r',label=title3)
    plotarray[2].set_title(title3)
    plt.gcf().autofmt_xdate()
    plt.show()

myTupleList = []
myList2 = []
myList3 = []
for x in range(100):
    y = random.random()*x
    myTupleList.append((x,y))
    if y > 5 and y <20:
        myList2.append(x)
    if y >20 and y <30:
        myList3.append(x)

graphIt(myTupleList,"MyTupleList",myList2,"MyList2",myList3,"MyList3")

Solution

  • Here is how you can do it:

    plotarray[0].set_ylim([50,100])
    

    I tested it with your code to make sure it works, and the top subplot has its y limits changed.