如何让图形在运行时打开一个新窗口?

2024-09-29 00:18:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望结果图在一个新窗口。我知道短语,%matplotlib inline将图形放入控制台,但是如果我删除它,它会给我错误

FigureCanvasMac' object has no attribute 'get_renderer.

有没有办法让我绕过这个问题?在

import re
import ftplib
import os
from urllib.request import urlopen
import json
import matplotlib
%matplotlib inline
import matplotlib.cm as cm
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, PathPatch
from matplotlib.path import Path
from matplotlib.transforms import Affine2D
import numpy as np
import pylab
import re
import sunpy.time
import numpy as np
from numpy.random import *
from matplotlib.patches import Rectangle
from adjustText import adjust_text
import pandas as pd
from scipy import interpolate
import sys

info = []
parsedFilename = []
dateAndTime = []
xcen = []
ycen = []
sciObj = []
xfov = []
yfov = []
matchingAR = []

def getNumberOfEntries(theJSON):
    return len(dateAndTime)   

def getInfo(counter, theJSON):
    cont = True
    while cont:
        try:
            dateAndTime.append(theJSON["Events"][counter]["date"])
            xcen.append(float("%.2f" % theJSON["Events"][counter]["xCen"]))
            ycen.append(float("%.2f" % theJSON["Events"][counter]["yCen"]))
            xfov.append(float("%.2f" % theJSON["Events"][counter]["raster_fovx"]))
            yfov.append(float("%.2f" % theJSON["Events"][counter]["raster_fovy"]))
            sciObj.append(theJSON["Events"][counter]["sciObjectives"])
            counter = counter + 1
            getInfo(counter, theJSON)
        except IndexError:
            cont = False
        break

def setXMax(theJSON):      
    xmax = xcen[0]
    for i in range (0, getNumberOfEntries(theJSON)):
        if xcen[i] > xmax:
            xmax = xcen[i]
    return round(xmax + 150,-1)

def setXMin(theJSON):
    xmin = xcen[0]
    for i in range (0, getNumberOfEntries(theJSON)):
        if xcen[i] < xmin:
            xmin = xcen[i]
    return round(xmin - 150, -1)

def setYMax(theJSON):      
    ymax = ycen[0]
    for i in range (0, getNumberOfEntries(theJSON)):
        if ycen[i] > ymax:
            ymax = ycen[i]
    return round(ymax + 150, -1)

def setYMin(theJSON):
    ymin = ycen[0]
    for i in range (0, getNumberOfEntries(theJSON)):
        if ycen[i] < ymin:
            ymin = ycen[i]
    return round(ymin - 150, -1)         

# def sort():
#     for i in range(len(dateAndTime)):
#         for j in range(len(xcen)-1, i, -1):
#             if ( xcen[j] < xcen[j-1]):
#                 temp1 = dateAndTime[j]
#                 dateAndTime[j] = dateAndTime[j-1]
#                 dateAndTime[j-1] = temp1

#                 temp2 = xcen[j]
#                 xcen[j] = xcen[j-1]
#                 xcen[j-1] = temp2

#                 temp3 = ycen[j]
#                 ycen[j] = ycen[j-1]
#                 ycen[j-1] = temp3

#                 temp4 = xfov[j]
#                 xfov[j] = xcen[j-1]
#                 xfov[j-1]=temp4

#                 temp5 = yfov[j]
#                 yfov[j] = ycen[j-1]
#                 yfov[j-1]=temp5

#                 temp6 = sciObj[j]
#                 sciObj[j] = sciObj[j-1]
#                 sciObj[j-1] = temp6

def sort():
    for i in range(len(dateAndTime)):
        for j in range(len(dateAndTime)-1, i, -1):
            if ( dateAndTime[j] < dateAndTime[j-1]):

                temp1 = dateAndTime[j]
                dateAndTime[j] = dateAndTime[j-1]
                dateAndTime[j-1] = temp1

                temp2 = xcen[j]
                xcen[j] = xcen[j-1]
                xcen[j-1] = temp2

                temp3 = ycen[j]
                ycen[j] = ycen[j-1]
                ycen[j-1] = temp3

                temp4 = xfov[j]
                xfov[j] = xcen[j-1]
                xfov[j-1]=temp4

                temp5 = yfov[j]
                yfov[j] = ycen[j-1]
                yfov[j-1]=temp5

                temp6 = sciObj[j]
                sciObj[j] = sciObj[j-1]
                sciObj[j-1] = temp6


def createAnnotations(theJSON):
    annotations = []
    for i in range(getNumberOfEntries(theJSON)):
        annotations.append('(' + str(xcen[i])+ ', '+ str(ycen[i]) + ')')

    return annotations

def fixAnnotations(annotations):
    texts = []
    for xt, yt, s in zip(xcen, ycen, annotations):
        texts.append(plt.text(xt, yt, s))
    return texts

def plot(theJSON):   
    fig, ax = plt.subplots(figsize=(30, 20))
    circle = Circle((0, 0), 980, facecolor='none', edgecolor=(0, 0.8, 0.8), linewidth=3, alpha=0.5)
    ax.add_patch(circle)

    plt.plot(xcen, ycen, color="red") 
    plt.plot(xcen, ycen, 'ro', color = 'blue')

    plt.xlim([setXMin(theJSON), setXMax(theJSON)])
    plt.ylim([setYMin(theJSON), setYMax(theJSON)])

    ax.set_xticks(np.arange(setXMin(theJSON), setXMax(theJSON), 50))
    ax.set_yticks(np.arange(setYMin(theJSON), setYMax(theJSON), 50))


    for i in range(getNumberOfEntries(theJSON)):
        if xfov[i] != 0:
            xStart = xcen[i] - xfov[i]/20
            yStart = ycen[i] - yfov[i]/20
            ax.add_patch(Rectangle((xStart, yStart), xfov[i]/10, yfov[i]/10, facecolor='none'))

    texts = fixAnnotations(createAnnotations(theJSON))

    f = interpolate.interp1d(xcen, ycen)
    x = np.linspace(min(xcen), max(ycen), 1000)
    y = f(x)
    adjust_text(texts, x, y, arrowprops=dict(arrowstyle="->", color='r', lw=2.0), autoalign='y', only_move={'points':'y', 'text':'y'}, expand_points=(1.2, 1.4), force_points=0.40)

    plt.grid()

    plt.show()
    main(False)

def searchOnceMore(searchAgain):
    if searchAgain == True:
        noaaNmbr = input('Enter desired active region: ')
        return noaaNmbr
    else:
        continueSearch = input('Would you like to search again?(yes/no)')
        if continueSearch == 'yes':
            noaaNmbr = input('Enter desired active region:')
            return noaaNmbr
        elif continueSearch == 'no':
            sys.exit(0)
        else:
            print('please enter "yes" or "no"')
            searchOnceMore(False)

def main(searchAgain):
    noaaNmbr = searchOnceMore(searchAgain)
    urlData = "http://www.lmsal.com/hek/hcr?cmd=search-events3&outputformat=json&instrument=IRIS&noaanum="+ noaaNmbr +"&hasData=true"
    webUrl = urlopen(urlData)
    counter = 0
    if (webUrl.getcode()==200):                
        data = webUrl.read().decode('utf-8')
        theJSON = json.loads(data)
        getInfo(counter, theJSON)
    else:
        print ("You done messed up!!!")

    sort()

    for i in range (getNumberOfEntries(theJSON)):
        print(dateAndTime[i])
        print("(", xcen[i], ", ", ycen[i], ")")
        print(sciObj[i])
        print(' ')

    if getNumberOfEntries(theJSON) != 0:
        plot(theJSON)
    else:
        print('No observations for active region ' + noaaNmbr)
        main()

main(True)

Tags: inimportforifmatplotlibdefcounterrange
1条回答
网友
1楼 · 发布于 2024-09-29 00:18:23

我也使用过python,建议使用johnzelle的图形文件。http://mcsp.wartburg.edu/zelle/python/ 在我看来,它更容易理解和使用。在

要打开新的图形窗口:

Win1 = GraphWin("Graph Window 1", 100,100)

win2 = GraphWin("Graph Window 2", 100,150)

您也可以打开python文件来了解它的工作原理。它可能有助于理解如何以您的方式打开图形窗口。我只知道如何通过这个文件打开一个新的图形窗口对不起,我希望它有帮助!在

相关问题 更多 >