了解用于创建图形的Matplotlib代码

时间:2018-07-12 21:14:36

标签: python matplotlib data-visualization

我找到了一篇博客文章,使用极坐标直方图显示了美国25个城市的街道网络方位:http://geoffboeing.com/2018/07/comparing-city-street-orientations/

作者提供了用于复制包含25个直方图的图形的代码(完整包含在此处:https://github.com/gboeing/osmnx-examples/blob/master/notebooks/17-street-network-orientations.ipynb)。

我想使用代码创建一个仅显示一个城市直方图的图形,但是当使用少于25个城市时,我会收到错误消息。

我以前没有使用过matplotlib,所以我认为问题出在代码中定义图中列和行数的部分,但是我不确定如何编辑它来做我想要的事情。 / p>

# create figure and axes
n = len(places)
ncols = int(np.ceil(np.sqrt(n)))
nrows = int(np.ceil(n / ncols))
figsize = (ncols * 5, nrows * 5)
fig, axes = plt.subplots(nrows, ncols, figsize=figsize, subplot_kw= 
{'projection':'polar'})
axes = [item for sublist in axes for item in sublist]

# plot each city's polar histogram
for ax, place in zip(axes, sorted(places.keys())):
polar_plot(ax, bearings[place], title=place)

# add super title and save full image
suptitle_font = {'family':'Century Gothic', 'fontsize':60, 
'fontweight':'normal', 'y':1.07}
fig.suptitle('City Street Network Orientation', **suptitle_font)
fig.tight_layout()
fig.subplots_adjust(hspace=0.35)
plt.gcf().savefig('images/street-orientations.png', dpi=120, 
bbox_inches='tight')
plt.close()

使用四个城市:

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-43-c59ecd43a7f0> in <module>()
     16 fig.tight_layout()
     17 fig.subplots_adjust(hspace=0.35)
---> 18 plt.gcf().savefig('images/street-orientations.png', dpi=120, 
        bbox_inches='tight')
     19 plt.close()

C:\PythonAnaconda\lib\site-packages\matplotlib\figure.py in savefig(self, 
fname, **kwargs)
   1832             self.set_frameon(frameon)
   1833 
-> 1834         self.canvas.print_figure(fname, **kwargs)
   1835 
   1836         if frameon:

C:\PythonAnaconda\lib\site-packages\matplotlib\backend_bases.py in 
print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, 
**kwargs)
   2265                 orientation=orientation,
   2266                 bbox_inches_restore=_bbox_inches_restore,
-> 2267                 **kwargs)
   2268         finally:
   2269             if bbox_inches and restore_bbox:

C:\PythonAnaconda\lib\site-packages\matplotlib\backends\backend_agg.py in 
print_png(self, filename_or_obj, *args, **kwargs)
    510         renderer.dpi = self.figure.dpi
    511         if isinstance(filename_or_obj, six.string_types):
--> 512             filename_or_obj = open(filename_or_obj, 'wb')
    513             close = True
    514         else:

FileNotFoundError: [Errno 2] No such file or directory: 'images/street- 
orientations.png'

使用一个城市:

TypeError                                 Traceback (most recent call last)
<ipython-input-58-c59ecd43a7f0> in <module>()
      5 figsize = (ncols * 5, nrows * 5)
      6 fig, axes = plt.subplots(nrows, ncols, figsize=figsize, subplot_kw= 
        {'projection':'polar'})
----> 7 axes = [item for sublist in axes for item in sublist]
      8 
      9 # plot each city's polar histogram

TypeError: 'PolarAxesSubplot' object is not iterable

2 个答案:

答案 0 :(得分:0)

如果只需要一个子图,则网格的行数和列数均为1

fig, axes = plt.subplots(nrows=1, ncols=1, figsize=figsize, subplot_kw= {'projection':'polar'})

然后您需要从代码中删除所有循环,因为axes是绘图中唯一的轴。

答案 1 :(得分:0)

以您的四个城市为例:创建一个images子文件夹以保存到其中。如果您提供的路径不存在,则matplotlib不会自动创建所有文件夹。

关于您的一个城市示例:如果您只使用一个轴进行单个绘图,则可以删除列表理解,因为您不需要展平原本是轴对象的numpy数组。