python怎么运行py文件( 三 )


plt.style.use(\'ggplot\')
我鼓励大家使用不同的风格,找到自己喜欢的 。
现在我们有了好看的风格,diyi步就是使用标准 pandas 绘图函数绘制数据:
top_10.plot(kind=\'barh\', y=\"Sales\", x=\"Name\")
推荐使用 pandas 绘图的原因在于它是一种快速便捷地建立可视化原型的方式 。
自定义图表
如果你对该图表的重要部分都很满意,那么下一步就是对它执行自定义 。一些自定义(如添加标题和标签)可以使用 pandas plot 函数轻松搞定 。但是,你可能会发现自己需要在某个时刻跳出来 。这就是我推荐你养成以下习惯的原因:
fig, ax = plt.subplots()
top_10.plot(kind=\'barh\', y=\"Sales\", x=\"Name\", ax=ax)
生成的图表和原始图表基本一样,不过我们向 plt.subplots() 添加了一个额外的调用,并将 ax 传输至绘图函数 。为什么要这么做呢?还记得我说在 Matplotlib 中获取轴和图像非常关键吗?这里所做的就是为了达到该目的 。通过 ax 或 fig 对象可以执行任何自定义 。
我们利用 pandas 实现快速绘图,现在利用 Matplotlib 获取所有功能 。通过使用命名惯例,调整别人的解决方案适应自己的需求变得更加直接简单了 。
假设我们想调整 x 极限,改变一些轴标签 。现在我们在 ax 变量中有多个轴,可以进行一些操作:
fig, ax = plt.subplots()
top_10.plot(kind=\'barh\', y=\"Sales\", x=\"Name\", ax=ax)
ax.set_xlim([-10000, 140000])
ax.set_xlabel(\'Total Revenue\')
ax.set_ylabel(\'Customer\');
这是另一种改变标题和标签的简单方式:
fig, ax = plt.subplots()
top_10.plot(kind=\'barh\', y=\"Sales\", x=\"Name\", ax=ax)
ax.set_xlim([-10000, 140000])
ax.set(title=\'2014 Revenue\', xlabel=\'Total Revenue\', ylabel=\'Customer\')
为了进一步展示该方法,我们还可以调整图像大小 。使用 plt.subplots() 函数可以定义 figsize,以英寸为单位 。我们还可以使用 ax.legend().set_visible(False) 移除图例 。
fig, ax = plt.subplots(figsize=(5, 6))
top_10.plot(kind=\'barh\', y=\"Sales\", x=\"Name\", ax=ax)
ax.set_xlim([-10000, 140000])
ax.set(title=\'2014 Revenue\', xlabel=\'Total Revenue\')
ax.legend().set_visible(False)
要想修改这个图像,你可能需要执行很多操作 。图中最碍眼的可能是总收益额的格式 。Matplotlib 可以使用 FuncFormatter 解决这一问题 。该函数用途多样,允许用户定义的函数应用到值,并返回格式美观的字符串 。
以下是货币格式化函数,用于处理数十万美元区间的数值:
def currency(x, pos):
\'The two args are the value and tick position\'
if x >= 1000000:
return \'${:1.1f}M\'.format(x*1e-6)
return \'${:1.0f}K\'.format(x*1e-3)
现在我们有了格式化程序函数,就需要定义它,并将其应用到 x 轴 。完整代码如下:
fig, ax = plt.subplots()
top_10.plot(kind=\'barh\', y=\"Sales\", x=\"Name\", ax=ax)
ax.set_xlim([-10000, 140000])
ax.set(title=\'2014 Revenue\', xlabel=\'Total Revenue\', ylabel=\'Customer\')
formatter = FuncFormatter(currency)
ax.xaxis.set_major_formatter(formatter)
ax.legend().set_visible(False)
这张图美观多了,非常好地展示了自定义问题解决方案的灵活性 。最后要说的自定义特征是向图表添加注释 。你可以使用 ax.axvline() 画垂直线,使用 ax.text() 添加自定义文本 。就以上示例,我们可以画一条表示平均值的线,包括代表 3 个新客户的标签 。以下是完整代码:
# Create the figure and the axes
fig, ax = plt.subplots()
# Plot the data and get the averaged
top_10.plot(kind=\'barh\', y=\"Sales\", x=\"Name\", ax=ax)
avg = top_10[\'Sales\'].mean()
# Set limits and labels


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