【问题标题】:How do I get the graph to open a new window when run?运行时如何让图表打开一个新窗口?
【发布时间】:2016-06-24 17:29:54
【问题描述】:

我希望生成的图表显示在新窗口中。我知道这句话,%matplotlib inline 将图表放在控制台中,但如果我删除它,它会给我错误

FigureCanvasMac' 对象没有属性 '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)

【问题讨论】:

  • 对于要回答的问题真的需要所有代码吗?
  • 你看过thisSO的帖子了吗?
  • 请提供一个最小的、可验证的示例来说明问题。人们不会费尽心思地通过 225 行代码来找到问题。
  • 好的抱歉,我会修复它

标签: python json matplotlib


【解决方案1】:

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

打开一个新的图表窗口:

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

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

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

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多