functionexportosmnxfig

phyton - Return Fig out of a function


Community, i play around with osmnx.

Part of the code is making a map in a function. After calling this object i want to ask user some questions to change BG Color and so on before saving.

So my code should look like:

from matplotlib import pyplot as plt
import networkx as nx
import osmnx as ox
import requests
import matplotlib.cm as cm
import matplotlib.colors as colors
from matplotlib.lines import Line2D
#import pillow as PIL


# To add text and a border to the map
from PIL import Image, ImageOps, ImageColor, ImageFont, ImageDraw 

north = latitude +0.04
south = latitude -0.10
east = longitude +0.10
west = longitude -0.08

def makemap (n, s, e, w):
    fig, ax = ox.plot_graph(G, node_size=0#, bbox = (n, s, e, w)
                       , dpi = 1200,  bgcolor = "#000038",
                        save = False, edge_color=roadColors,
                        edge_linewidth=roadWidths, edge_alpha=1)
    fig.tight_layout(pad=0)

     return fig
   
makemap(north, south, east, west)


#asking questions....


fig.savefig("%s.png"% (place), dpi=1200, bbox_inches='tight', format="png", facecolor=fig.get_facecolor())

Unfornatualy it wont let me save because it it dont find fig.

So i try return fig() - Then i get figure is not an callable object

It only works when i put the saving line into the function like:

north = latitude +0.04
south = latitude -0.10
east = longitude +0.10
west = longitude -0.08

def makemap (n, s, e, w):
    fig, ax = ox.plot_graph(G, node_size=0#, bbox = (n, s, e, w)
                       , dpi = 1200,  bgcolor = "#000038",
                        save = False, edge_color=roadColors,
                        edge_linewidth=roadWidths, edge_alpha=1)
    fig.tight_layout(pad=0)

     
    fig.savefig("%s.png"% (place), dpi=1200, bbox_inches='tight', format="png", facecolor=fig.get_facecolor())

makemap(north, south, east, west)


#asking questions....

But so i cant handle it the way i wanted it.

I try to find examples but it dont works for me. Can someone of the community help me out how to return fig?

Thanks in advance.


Solution

  • Assign what you return to a variable. In your first example change makemap(north, south, east, west) to fig = makemap(north, south, east, west).