参考资料:
《Python数据分析基础》,作者[美]Clinton W. Brownley,译者陈光欣,中国工信出版集团,人民邮电出版社
数据可视化主要旨在借助于图形化手段,清晰有效地传达与沟通信息。它可以使我们看到变量的分布和变量之间的关系,还可以检查建模过程中的假设。
Python提供了若干种用于绘图的扩展包,包括matplotlib, pandas, ggplot和seaborn。
这一节主要对matplotlib进行学习。
有关matplotlib的相关函数及说明,可以参考我以前写的两篇博客:《【总结篇】Python matplotlib之使用函数绘制matplotlib的图表组成元素》《【总结篇】Python matplotlib之使用统计函数绘制简单图形》。
使用matplotlib绘制条形图
代码如下:
#!/usr/bin/env python3 import matplotlib.pyplot as plt plt.style.use('ggplot') # 使用ggplot样式表来模拟ggplot2风格的图形 # 为条形图准备数据 customers = ['ABC', 'DEF', 'GHI', 'JKL', 'MNO'] customers_index = range(len(customers)) sale_amounts = [127, 90, 201, 111, 232] # 绘图 fig = plt.figure() # 创建了一个基础图 ax1 = fig.add_subplot(1, 1, 1) # 在基础图中创建1行1列的子图,并使用第1个也是唯一的一个子图 ax1.bar(customers_index, sale_amounts, align='center', color='darkblue') # 创建条形图 ax1.xaxis.set_ticks_position('bottom') # x刻度线位置 ax1.yaxis.set_ticks_position('left') # y刻度线位置 plt.xticks(customers_index, customers, rotation=0, fontsize='small') # 将刻度线标签更改为实际的客户名称 plt.xlabel('Customer Name') # 添加x轴标签 plt.ylabel('Sale Amount') # 添加y轴标签 plt.title('Sale Amount per Customer') # 添加图形标题 plt.savefig('bar_plot.png', dpi=400, bbox_inches='tight') # 保存统计图到当前文件夹 plt.show()
123456789101112131415161718192021222324Tips:
ax1.bar(customers_index, sale_amounts, align=‘center’, color&#