OSMnx Add Title to Graph Plot

我们两清 提交于 2020-01-06 05:59:15

问题


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.



来源:https://stackoverflow.com/questions/48799928/osmnx-add-title-to-graph-plot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!