python怎么运行py文件( 四 )


ax.set_xlim([-10000, 140000])
ax.set(title=\'2014 Revenue\', xlabel=\'Total Revenue\', ylabel=\'Customer\')
# Add a line for the average
ax.axvline(x=avg, color=\'b\', label=\'Average\', linestyle=\'--\', linewidth=1)
# Annotate the new customers
for cust in [3, 5, 8]:
ax.text(115000, cust, \"New Customer\")
# Format the currency
formatter = FuncFormatter(currency)
ax.xaxis.set_major_formatter(formatter)
# Hide the legend
ax.legend().set_visible(False)
这可能不是最壮观的图,但它确实展示了使用该方法的力量 。
图表
目前,我们所做的所有改变都是针对单个图表 。我们还能够在图像上添加多个表,使用不同的选项保存整个图像 。
如果我们确定要在同一个图像上放置两个表,那么我们应该对如何做有一个基础了解 。首先,创建图像,然后创建轴,再将它们绘制成图表 。使用 plt.subplots() 可以完成该操作:
fig, (ax0, ax1) = plt.subplots(nrows=1, ncols=2, sharey=True, figsize=(7, 4))
在这个例子中,我使用 nrows 和 ncols 指定大小,这对新用户来说比较清晰易懂 。
在示例代码中,你会经常看到变量如 1、2 。我认为使用命名参数便于稍后查看代码时理解代码 。
我还使用 sharey=True 以使 y 轴共享相同的标签 。
该示例很灵活,因为不同的轴可以解压成 ax0 和 ax1 。现在我们有了这些轴,就可以像上述示例中那样绘图,然后把一个图放在 ax0 上,另一个图放在 ax1 。
# Get the figure and the axes
fig, (ax0, ax1) = plt.subplots(nrows=1,ncols=2, sharey=True, figsize=(7, 4))
top_10.plot(kind=\'barh\', y=\"Sales\", x=\"Name\", ax=ax0)
ax0.set_xlim([-10000, 140000])
ax0.set(title=\'Revenue\', xlabel=\'Total Revenue\', ylabel=\'Customers\')
# Plot the average as a vertical line
avg = top_10[\'Sales\'].mean()
ax0.axvline(x=avg, color=\'b\', label=\'Average\', linestyle=\'--\', linewidth=1)
# Repeat for the unit plot
top_10.plot(kind=\'barh\', y=\"Purchases\", x=\"Name\", ax=ax1)
avg = top_10[\'Purchases\'].mean()
ax1.set(title=\'Units\', xlabel=\'Total Units\', ylabel=\'\')
ax1.axvline(x=avg, color=\'b\', label=\'Average\', linestyle=\'--\', linewidth=1)
# Title the figure
fig.suptitle(\'2014 Sales Analysis\', fontsize=14, fontweight=\'bold\');
# Hide the legends
ax1.legend().set_visible(False)
ax0.legend().set_visible(False)
现在,我已经在 jupyter notebook 中用 %matplotlib inline 展示了很多图像 。但是,在很多情况下你需要以特定格式保存图像,将其和其他呈现方式整合在一起 。
Matplotlib 支持多种不同文件保存格式 。你可以使用 fig.canvas.get_supported_filetypes() 查看系统支持的文件格式:
fig.canvas.get_supported_filetypes()
{\'eps\': \'Encapsulated Postscript\',
\'jpeg\': \'Joint Photographic Experts Group\',
\'jpg\': \'Joint Photographic Experts Group\',
\'pdf\': \'Portable Document Format\',
\'pgf\': \'PGF code for LaTeX\',
\'png\': \'Portable Network Graphics\',
\'ps\': \'Postscript\',
\'raw\': \'Raw RGBA bitmap\',
\'rgba\': \'Raw RGBA bitmap\',
\'svg\': \'Scalable Vector Graphics\',
\'svgz\': \'Scalable Vector Graphics\',
\'tif\': \'Tagged Image File Format\',
\'tiff\': \'Tagged Image File Format\'}
我们有 fig 对象,因此我们可以将图像保存成多种格式:
fig.savefig(\'sales.png\', transparent=False, dpi=80, bbox_inches=\"tight\")
该版本将图表保存为不透明背景的 png 文件 。我还指定 dpi 和 bbox_inches=\"tight\" 以最小化多余空白 。
结论
【python怎么运行py文件】希望该方法可以帮助大家理解如何更有效地使用 Matplotlib 进行日常数据分析 。


特别声明:本站内容均来自网友提供或互联网,仅供参考,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。