-->

OSMnx Add Title to Graph Plot

2019-08-26 13:39发布

问题:

I'm using the wonderful OSMnx library created by Geoff Boeing. I am plotting a street network based on one of his tutorials. Everything works perfectly. However, I would like to plot more than 40 graphs, using different centralities. Therefore, I would like to add a title with each district and centrality name to each plot. Currently, it looks like this.

Plotted OSMnx Street Network

This is what my code looks like.

def display_most_important_node(G_centralities_sorted_dict, G_dictionary, district, centrality_measure='betweenness_centrality'):
    node_color = ['red' if node == G_centralities_sorted_dict[district][centrality_measure][0][0] else '#336699' for node in ox.project_graph(G_dictionary[district]).nodes()]
    node_size = [40 if node == G_centralities_sorted_dict[district][centrality_measure][0][0] else 20 for node in ox.project_graph(G_dictionary[district]).nodes()]

    fig, ax = ox.plot_graph(ox.project_graph(G_dictionary[district]), annotate=False, edge_linewidth=1.5, node_size=node_size, fig_height=10, node_color=node_color, node_zorder=2)

Thank you guys.

回答1:

By default, the functions of the OSMnx package call plt.show() already before they return the fig and ax handles, which means you can no longer manipulate the Figure and Axes instances (my guess is that this is done to prevent distortion of the Figure after creation). This is done using a special function called save_and_show(), which is called internally. You can prevent the showing of the figure by passing the keywords show=False and close=False to the according plotting function (close=False is needed because figures that are not automatically shown are by default closed within save_and_show()). With these keywords used, fig and ax can be manipulated after the function call, but now plt.show() has to be called explicitly. Here still a complete example following the OP:

def display_most_important_node(G_centralities_sorted_dict, G_dictionary, district, centrality_measure='betweenness_centrality'):
    node_color = ['red' if node == G_centralities_sorted_dict[district][centrality_measure][0][0] else '#336699' for node in ox.project_graph(G_dictionary[district]).nodes()]
    node_size = [40 if node == G_centralities_sorted_dict[district][centrality_measure][0][0] else 20 for node in ox.project_graph(G_dictionary[district]).nodes()]

    fig, ax = ox.plot_graph(ox.project_graph(G_dictionary[district]), annotate=False, edge_linewidth=1.5, node_size=node_size, fig_height=10, node_color=node_color, node_zorder=2, show=False, close=False)

    ax.set_title('subplot title')
    fig.suptitle('figure title')
    plt.show()

Note that not all OSMnx functions accept the show and close keywords. For instance, plot_shape does not. Hope this helps.