matplotlib รับค่า ylim


115

ฉันใช้matplotlibเพื่อลงจุดข้อมูล (โดยใช้plotและerrorbarฟังก์ชัน) จาก Python ฉันต้องพล็อตชุดของพล็อตที่แยกจากกันและเป็นอิสระจากนั้นปรับylimค่าเพื่อให้สามารถเปรียบเทียบด้วยสายตาได้ง่าย

ฉันจะดึงylimค่าจากแต่ละพล็อตได้อย่างไรเพื่อให้ฉันสามารถหาค่า min และ max ของค่า ylim ล่างและบนตามลำดับและปรับพล็อตเพื่อให้สามารถเปรียบเทียบด้วยสายตาได้

แน่นอนฉันสามารถวิเคราะห์ข้อมูลและหาylimค่าที่กำหนดเองได้... แต่ฉันต้องการใช้matplotlibเพื่อทำเช่นนั้น ข้อเสนอแนะเกี่ยวกับวิธีการทำสิ่งนี้อย่างง่ายดาย (และมีประสิทธิภาพ) หรือไม่?

นี่คือฟังก์ชัน Python ของฉันที่ใช้matplotlib:

import matplotlib.pyplot as plt

def myplotfunction(title, values, errors, plot_file_name):

    # plot errorbars
    indices = range(0, len(values))
    fig = plt.figure()
    plt.errorbar(tuple(indices), tuple(values), tuple(errors), marker='.')

    # axes
    axes = plt.gca()
    axes.set_xlim([-0.5, len(values) - 0.5])
    axes.set_xlabel('My x-axis title')
    axes.set_ylabel('My y-axis title')

    # title
    plt.title(title)

    # save as file
    plt.savefig(plot_file_name)

    # close figure
    plt.close(fig)

คำตอบ:


159

เพียงแค่ใช้axes.get_ylim()ก็คล้ายกับset_ylim. จากเอกสาร :

get_ylim ()

รับช่วงแกน y [ด้านล่างด้านบน]


2
มีวิธีรับขีด จำกัด พื้นที่กราฟมากกว่าขีด จำกัด แกนหรือไม่? กรอบสี่เหลี่ยมสีดำอยู่เหนือค่าเหล่านี้เล็กน้อย
Peter Ehrlich

@PeterEhrlich นั่นเป็นเพียงระยะขอบ
ilija139

12
ฉันคิดว่าplt.gca().get_ylim()มีประโยชน์ - ไม่จำเป็นต้องมีการกำหนดแกนเพิ่มเติม
Matthias Arras

อีกวิธีหนึ่งคือฉันชอบใช้fig, ax = plt.subplots()แล้วกำหนดเส้นทางฟังก์ชั่นทั้งหมดของฉันผ่านอย่างใดอย่างหนึ่งfigหรือax
BallpointBen

34
 ymin, ymax = axes.get_ylim()

หากคุณใช้pltapi โดยตรงคุณสามารถหลีกเลี่ยงการโทรไปยังแกนได้ทั้งหมด:

def myplotfunction(title, values, errors, plot_file_name):

    # plot errorbars
    indices = range(0, len(values))
    fig = plt.figure()
    plt.errorbar(tuple(indices), tuple(values), tuple(errors), marker='.')

    plt.xlim([-0.5, len(values) - 0.5])
    plt.xlabel('My x-axis title')
    plt.ylabel('My y-axis title')

    # title
    plt.title(title)

    # save as file
    plt.savefig(plot_file_name)

   # close figure
    plt.close(fig)

10

ใช้ประโยชน์จากคำตอบที่ดีข้างต้นและสมมติว่าคุณใช้ plt ในรูปเท่านั้น

import matplotlib.pyplot as plt

จากนั้นคุณจะได้รับขีด จำกัด พล็อตทั้งสี่โดยใช้plt.axis()ดังตัวอย่างต่อไปนี้

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5, 6, 7, 8]  # fake data
y = [1, 2, 3, 4, 3, 2, 5, 6]

plt.plot(x, y, 'k')

xmin, xmax, ymin, ymax = plt.axis()

s = 'xmin = ' + str(round(xmin, 2)) + ', ' + \
    'xmax = ' + str(xmax) + '\n' + \
    'ymin = ' + str(ymin) + ', ' + \
    'ymax = ' + str(ymax) + ' '

plt.annotate(s, (1, 5))

plt.show()

โค้ดด้านบนควรสร้างพล็อตเอาต์พุตต่อไปนี้ ใส่คำอธิบายภาพที่นี่

โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.