Matplotlib 是 Python 的绘图库。 它可与 NumPy 一起使用,提供了一种有效的 MatLab 开源替代方案。 它也可以和图形工具包一起使用,如 PyQt 和 wxPython。
另一篇可视化案例《python机器学习经典实例》——可视化数据
一个完整的图形的表现需要的标准开发步骤:
*******画一朵花*******
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
[x, t] = np.meshgrid(np.array(range(25))/24.0, np.arange(0, 575.5, 0.5)/575*17*np.pi-2*np.pi)
p = (np.pi/2)*np.exp(-t/(8*np.pi))
u = 1-(1-np.mod(3.6*t, 2*np.pi)/np.pi)**4/2
y = 2*(x**2-x)**2*np.sin(p)
r = u*(x*np.sin(p)+y*np.cos(p))
surf = ax.plot_surface(r*np.cos(t), r*np.sin(t), u*(x*np.cos(p)-y*np.sin(p)),rstride=1, cstride=1, cmap=cm.gist_rainbow_r, linewidth=0, antialiased=True)
plt.show()
这是一个csv文件,失业率数据。
数据格式化(将日期转化格式):
import pandas as pd
unrate=pd.read_csv('unrate.csv')
unrate['DATE']=pd.to_datetime(unrate['DATE'])
print(unrate.head(10))
画出空白坐标图:
import matplotlib.pyplot as plt
plt.plot()
plt.show()
取出数据中的前12条数据,在将这12条数据,分别画入,X轴,Y轴到图中,显示出来,
import pandas as pd
import matplotlib.pyplot as plt
unrate=pd.read_csv('unrate.csv')
unrate['DATE']=pd.to_datetime(unrate['DATE'])
#print(unrate.head(12))
#画出前12个月
first_twelve=unrate[0:12]
plt.plot(first_twelve['DATE'],first_twelve['VALUE'])
plt.show()
运行结果:
plt.xticks(rotation=)x坐标轴的度数,可以使图表变得美观。
import pandas as pd
import matplotlib.pyplot as plt
unrate=pd.read_csv('unrate.csv')
unrate['DATE']=pd.to_datetime(unrate['DATE'])
#print(unrate.head(12))
#画出前12个月
first_twelve=unrate[0:12]
plt.plot(first_twelve['DATE'],first_twelve['VALUE'])
plt.xticks(rotation=45)
plt.show()
plt.xlabel() plt.ylabel() plt.title() 添加横、纵坐标标签及折线图标题
import pandas as pd
import matplotlib.pyplot as plt
unrate=pd.read_csv('unrate.csv')
unrate['DATE']=pd.to_datetime(unrate['DATE'])
#print(unrate.head(12))
#画出前12个月
first_twelve=unrate[0:12]
plt.plot(first_twelve['DATE'],first_twelve['VALUE'])
plt.xticks(rotation=90)
plt.xlabel('Month')
plt.ylabel('Unemployment Rate')
plt.title("Monthly Unemployment Trends 1948")
plt.show()
fig=plt.figure()创建一个画图对象,相当于一个画图区域
fig.add_subplot(4, 3, 1) 前面两个数字代表行数,列数,最后一个数字代表第几个图,从左到右,从上到下看
import matplotlib.pyplot as plt
fig=plt.figure()
ax1=fig.add_subplot(4,3,1)
ax2=fig.add_subplot(4,3,2)
ax2=fig.add_subplot(4,3,6)
plt.show()
随机画一些东西
import numpy as np
import matplotlib.pyplot as plt
fig=plt.figure()
ax1=fig.add_subplot(4,3,1)
ax2=fig.add_subplot(4,3,2)
ax2=fig.add_subplot(4,3,6)
ax1.plot(np.random.randint(1,5,5),np.arange(5))
ax2.plot(np.arange(10)*3,np.arange(10))
plt.show()
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
unrate=pd.read_csv('UNRATE.csv')
unrate['DATE']=pd.to_datetime(unrate['DATE'])
#print(unrate.head(3))
unrate['MONTH']=unrate['DATE'].dt.month
fig=plt.figure(figsize=(6,3))
plt.plot(unrate[0:12]['MONTH'],unrate[0:12]['VALUE'],c='red')
plt.plot(unrate[12:24]['MONTH'],unrate[12:24]['VALUE'],c='blue')
plt.show()
画出每一年的浮动情况:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
unrate=pd.read_csv('UNRATE.csv')
unrate['DATE']=pd.to_datetime(unrate['DATE'])
#print(unrate.head(3))
unrate['MONTH']=unrate['DATE'].dt.month
fig=plt.figure(figsize=(10,6))
colors=['red','blue','green','orange','black']
for i in range(5):
start_index=i*12
end_index=(i+1)*12
subset=unrate[start_index:end_index]
label=str(1948+i)
plt.plot(subset['MONTH'],subset['VALUE'],c=colors[i],label=label)
plt.legend(loc='best')
plt.show()
plt. legend(loc='best')标签位置
运行结果:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
reviews=pd.read_csv('fandango_scores.csv')
cols=['FILM','RT_user_norm','Metacritic_user_nom','IMDB_norm','Fandango_Ratingvalue','Fandango_Stars']
norm_reviews=reviews[cols]
#print(norm_reviews[:1])
num_cols = ['RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm', 'Fandango_Ratingvalue', 'Fandango_Stars']
bar_heights=norm_reviews.ix[0,num_cols].values
#print(bar_heights)
bar_position=np.arange(5)+0.75
tick_position=range(1,6)
#print(bar_position)
fig,ax=plt.subplots()
ax.bar(bar_position,bar_heights,0.5)
ax.set_xticks(tick_position)
ax.set_xticklabels(num_cols,rotation=45)
ax.set_xlabel("Rating Source")
ax.set_ylabel("Average Rating")
ax.set_title("Average User Rating For Avengers: Age of Ultron (2015)")
plt.show()
要想横着画,只需稍作改动:
import pandas as pd
import matplotlib.pyplot as plt
reviews=pd.read_csv('fandango_scores.csv')
cols=['FILM','RT_user_norm','Metacritic_user_nom','IMDB_norm','Fandango_Ratingvalue','Fandango_Stars']
norm_reviews=reviews[cols]
fig,ax=plt.subplots()
ax.scatter(norm_reviews['Fandango_Ratingvalue'],norm_reviews['RT_user_norm'])
ax.set_xlabel('Fandango')
ax.set_ylabel('Rotten Tomatoes')
plt.show()
import numpy as np
from matplotlib import pyplot as plt
plt.figure(figsize=(9,6))
n = 8
X = np.arange(n)+1
#X是1,2,3,4,5,6,7,8,柱的个数
# numpy.random.uniform(low=0.0, high=1.0, size=None), normal
#uniform均匀分布的随机数,normal是正态分布的随机数,0.5-1均匀分布的数,一共有n个
Y1 = np.random.uniform(0.5,1.0,n)
Y2 = np.random.uniform(0.5,1.0,n)
plt.bar(X,Y1,width = 0.35,facecolor = 'lightskyblue',edgecolor = 'white')
#width:柱的宽度
plt.bar(X+0.35,Y2,width = 0.35,facecolor = 'yellowgreen',edgecolor = 'white')
#水平柱状图plt.barh,属性中宽度width变成了高度height
#打两组数据时用+
#facecolor柱状图里填充的颜色
#edgecolor是边框的颜色
#想把一组数据打到下边,在数据前使用负号
#plt.bar(X, -Y2, width=width, facecolor='#ff9999', edgecolor='white')
#给图加text
for x,y in zip(X,Y1):
plt.text(x+0.3, y+0.05, '%.2f' % y, ha='center', va= 'bottom')
for x,y in zip(X,Y2):
plt.text(x+0.6, y+0.05, '%.2f' % y, ha='center', va= 'bottom')
plt.ylim(0,+1.25)
plt.show()
#Color
import pandas as pd
import matplotlib.pyplot as plt
women_degrees = pd.read_csv('percent-bachelors-degrees-women-usa.csv')
major_cats = ['Biology', 'Computer Science', 'Engineering', 'Math and Statistics']
cb_dark_blue = (0/255, 107/255, 164/255)
cb_orange = (255/255, 128/255, 14/255)
fig = plt.figure(figsize=(12, 12))
for sp in range(0,4):
ax = fig.add_subplot(2,2,sp+1)
# The color for each line is assigned here.
ax.plot(women_degrees['Year'], women_degrees[major_cats[sp]], c=cb_dark_blue, label='Women')
ax.plot(women_degrees['Year'], 100-women_degrees[major_cats[sp]], c=cb_orange, label='Men')
for key,spine in ax.spines.items():
spine.set_visible(False)
ax.set_xlim(1968, 2011)
ax.set_ylim(0,100)
ax.set_title(major_cats[sp])
ax.tick_params(bottom="off", top="off", left="off", right="off")
plt.legend(loc='upper right')
plt.show()
#-*- coding:utf-8 -*-
# 步骤1:导入相关的模块库
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
# 补充:设置图表中文的正常显示
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 解决中文乱码
mpl.rcParams['axes.unicode_minus']=False # 解决负号乱码
# 步骤2:创建3D的容器空间
# 创建一个图对象
figure = plt.figure()
# 购进3D图表对象
ax = Axes3D(figure)
# 步骤3:设置相关的数据集
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
# Z轴值的获取
# 将X、Y轴值的两个一维数据集整合成一个二维数据集
X, Y = np.meshgrid(X, Y)
# 根据R系数书生成Z轴数据
R = np.sqrt(X**2 + Y**2)
# 得到Z轴的轴值
Z = np.sin(R)
# 步骤4:生成正弦曲面图
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='rainbow')
# 设置图表的标题
ax.set_title("图1:正弦曲面3D图表")
# 步骤5:输出图片
plt.show()
#-*- coding:utf-8 -*-
# 步骤1:导入相关模块库
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
# 补充:设置图表中文的正常显示
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 解决中文乱码
mpl.rcParams['axes.unicode_minus']=False # 解决负号乱码
# 步骤2:获取数据
data = np.random.randint(0, 255, size=[40,40,40])
x, y, z = data[0], data[1], data[2]
# 创建一个三维的工程空间
ax = plt.subplot(111, projection='3d')
# 步骤3:拆分绘图所需要的坐标数据集
ax.scatter(x[:10], y[:10], z[:10], c="y")
ax.scatter(x[10:20], y[10:20], z[10:20], c="b")
ax.scatter(x[30:40], y[30:40], z[30:40], c="g")
# 步骤4:设置图表的相关辅助参数
ax.set_title("图2:散点图3D绘制-随机漫步")
# 步骤5:输出图表
plt.show()
#-*- coding:utf-8 -*-
# 步骤1:导入相关模块库
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
# 补充:设置图表中文的正常显示
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 解决中文乱码
mpl.rcParams['axes.unicode_minus']=False # 解决负号乱码
# 步骤2:获取数据
x = np.linspace(-6 * np.pi, 6 * np.pi, 1000)
y = np.sin(x)
z = np.cos(x)
# 步骤3:构建三维空间
figure = plt.figure()
ax = Axes3D(figure)
# 步骤4:绘制图形
ax.plot(x, y, z)
# 步骤5:设置标题
ax.set_title("图3:3D曲线图")
# 步骤6:输出图形
plt.show()
#-*- coding:utf-8 -*-
# 步骤1:导入相关模块库
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
# 补充:设置图表中文的正常显示
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 解决中文乱码
mpl.rcParams['axes.unicode_minus']=False # 解决负号乱码
# 步骤2:获取数据
x = [0, 1, 2, 3, 4, 5, 6]
# 步骤3:构建三维空间
figure = plt.figure()
ax = Axes3D(figure)
# 步骤4:绘制图形
for i in x:
y = [0,1,2,3,4,5,6,7,8,9]
z = abs(np.random.normal(1, 10, 10))
ax.bar(y, z, i, zdir='y', color=['r', 'g', 'b', 'y'])
pass
# 步骤5:设置标题
ax.set_title("图4:3D柱状图")
# 步骤6:输出图形
plt.show()