Matplotlib绘图
1.绘制散点图
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
#绘制简单的散点图
x = np.random.randn(1000)
y = np.random.randn(1000)
plt.scatter(x,y)
plt.title('scatter')
plt.show()
使用numpy.random模块中的randn函数生成两组数据,使用scatter函数绘制散点图.
#使用scatter函数绘制星形散点图
x = np.random.randn(1000)
y = np.random.randn(1000)
plt.scatter(x,y,color='g',marker='*',alpha=0.5)
plt.title('scatter')
plt.show()
# 调整坐标轴范围
x = np.random.randn(1000)
y = np.random.randn(1000)
plt.scatter(x,y,color='g',marker='*',alpha=0.5)
plt.title('scatter')
plt.xlim(-5,5)
plt.ylim(-5,5)
plt.show()
2.绘制折线图
#绘制折线图
growth = pd.read_table('growth.txt',sep=' ',encoding='utf-8')
print(growth.head(5))
Year Australia Austria Belgium Finland Germany \
0 1946 -3.557951 * * 8.132124 *
1 1947 2.459475 * 15.2163021098959 2.324528 *
2 1948 6.437534 27.3291925465839 11.4405542270448 7.928714 *
3 1949 6.611994 18.9024390243902 -1.30662891505271 6.066839 *
4 1950 6.920201 12.4089618396898 5.64131712126092 3.844582 *
Ireland Italy Japan Netherlands New Zealand Norway \
0 * * * * 7.711320 10.201270
1 1.89473684210526 * * * 11.932079 13.562973
2 4.86080904741193 * * * -9.922099 6.951517
3 5.23695945245255 * * * 10.787437 2.667090
4 0.817895151754033 * * * 14.675949 4.870087
Sweden UK US
0 11.399403 -2.458310 -10.942159
1 7.936645 -1.276224 -0.898337
2 2.315780 2.924110 4.397275
3 2.949126 3.314717 -0.512350
4 6.007847 3.181459 8.743969
#使用matplotlib.pyplot中的plot函数绘制瑞典、挪威、新西兰的实际GDP增长折线图。
plt.plot(growth['Year'], growth['Sweden'], color = 'r', label = 'Sweden',linestyle = '--')
plt.plot(growth['Year'], growth['Norway'], color = 'pink', label = 'Norway')
plt.plot(growth['Year'], growth['New Zealand'], color = 'purple', label = 'New Zealand',marker = '+')
plt.title('Real GDP Growth for Three Countries between 1946 and 2009')
plt.xlabel('Year')
plt.ylabel('Real GDP Growth')
plt.legend()
plt.show()
3 绘制柱状图
#柱状图
index = np.arange(5)
value = [20,30,45,35,50]
plt.bar(index, value, width = 0.5, label = 'population', facecolor = '#ff0000')
plt.title('Grouping Allocation')
plt.xticks(index, ('Group1','Group2','Group3','Group4','Group5'))
plt.yticks(np.arange(0,60,10))
plt.legend(loc='upper left')
a = zip(index,value)
for x,y in a:
plt.text(x, y, y, ha='center', va='bottom')
plt.show()
4 绘制箱线图
#绘制箱线图
goals = pd.read_csv('WorldCupMatches.csv')
home_team_goals = goals['Home Team Goals']
away_team_goals = goals['Away Team Goals']
plt.boxplot((home_team_goals,away_team_goals), labels = ['Home Teams','Away Teams'])
plt.title('Goals for Home Teams and Away Teams in all FIFA World Cups')
plt.show()
参考书籍:
Python 3 快速入门与实战