1 散点图
alpha表示透明度
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# height=[161,170,182,175,173,165]
# weight=[50,58,80,70,69,55]
# plt.scatter(height,weight)
# plt.show()
N = 1000
# x = np.random.randn(N)
# y1 = np.random.randn(N)
# plt.scatter(x,y1)
# plt.show()
# x = np.random.randn(N)
# y = -x+np.random.randn(N)*0.5
# plt.scatter(x,y)
# plt.show()
open,close=np.loadtxt('000001.csv',delimiter=',',skiprows=1,usecols=(1,4),unpack=True)
change = close - open
yesterday = change[:-1]
today = change[1:]
plt.scatter(yesterday,today,s=200,c="r",marker = "<",alpha=0.5)
plt.show()
2 折线图
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# x = np.linspace(-10,10,5)
# y = x**2
# plt.plot(x,y)
# plt.show()
# date,open,close=np.loadtxt('000001.csv',delimiter=',',
# converters={0:mdates.bytespdate2num('%m/%d/%Y')},skiprows=1,usecols=(0,1,4),unpack=True)
#
# plt.plot_date(date,open,linestyle = "-",color="r",marker="o")
# plt.plot_date(date,close,linestyle = "-",color="g",marker="o")
# plt.show()
date,open,high,low,close=np.loadtxt('000001.csv',delimiter=',',
converters={0:mdates.bytespdate2num('%m/%d/%Y')},skiprows=1,usecols=(0,1,2,3,4),unpack=True)
plt.plot_date(date,high,linestyle = "--",color="r",marker="o")
plt.plot_date(date,low,linestyle = "--",color="b",marker="o")
plt.plot_date(date,open,linestyle = "-",color="g",marker="o")
plt.plot_date(date,close,linestyle = "-",color="y",marker="o")
plt.show()
3 条形图
bottom表示最低点从哪儿开始
import numpy as np
import matplotlib.pyplot as plt
N=5
# y1 = [20,10,30,25,15]
# index = np.arange(N)
# # pl = plt.bar(x=index,height=y,bottom=2,color="r",width = 0.5)
# pl = plt.barh(y=index,height=0.5,width=y1)
index = np.arange(4)
sales_BJ=[52,55,63,53]
sales_SH=[44,66,55,41]
bar_width = 0.3
# plt.bar(index,sales_BJ,bar_width,color='b')
# plt.bar(index+bar_width,sales_SH,bar_width,color='r')
# plt.show()
plt.bar(index,sales_BJ,bar_width,color='b')
plt.bar(index,sales_SH,bar_width,color='r',bottom=sales_BJ)
plt.show()
4 直方图
频率和频次由density密度控制
单变量
双变量
import numpy as np
import matplotlib.pyplot as plt
import os
os.chdir("E:\\A21\\New_python\\数据可视化")
# mu = 100
# sigma = 20
# x = mu + sigma * np.random.randn(20000)
#
# plt.hist(x=x,bins=500,color="g",density=True)
# # plt.hist(x=x,bins=500,color="r")
# plt.show()
# x = np.random.randn(1000)+2
# y = np.random.randn(1000)+3
#
# plt.hist2d(x,y,bins=40)
#
# plt.show()
x = np.random.randn(2000)+1
y = np.random.randn(2000)+5
plt.hist2d(x,y,bins=20)
plt.show()
5 饼状图
explode表示距离中心距离,可突出显示某一块
autopct加上百分比
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
labels = "A","B","C","D"
fracs = [15, 30, 45, 10]
explode = [0.1,0,0.08,0]
plt.axes(aspect=1)
plt.pie(x=fracs,labels=labels,autopct="%.0f%%",explode=explode,shadow=True)
plt.show()
6 箱线图
whis表示异常值显示多少,越小显示越多
sym表示异常点的形状
whis =1
whis =2
多个箱线图(最后生成的二维数组代码)
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(100)
# data = np.random.normal(size=1000, loc=0.0, scale=1.0)
#
# plt.boxplot(data,sym='o',whis=1) #sym调整异常值点的形状,whis虚线长度
#
# plt.show()
data = np.random.normal(size=(100, 4), loc=0.0, scale=1.0)
labels = ['A','B','C','D']
plt.boxplot(data, labels=labels)
plt.show()
7 颜色和样式
7.1 颜色
颜色表示方法:字母,十六进制,灰度,RGB元组
注意:搜索颜色代码可查询所有
import numpy as np
import matplotlib.pyplot as plt
y=np.arange(1,5)
plt.plot(y,color="m") #默认颜色表示
plt.plot(y+1,color="0.5") #灰度
plt.plot(y+2,color="#FF00FF") #十六进制
plt.plot(y+3,color=(0.1,0.2,0.3)) #RGB
plt.show()
7.2 点
指不指定marker决定有无线条
import numpy as np
import matplotlib.pyplot as plt
y=np.arange(1,5)
plt.plot(y,marker="o") #默认颜色表示
plt.plot(y+1,marker="D") #灰度
plt.plot(y+2,marker="*") #十六进制
plt.plot(y+3,"p") #RGB
plt.show()
7.3 线
import numpy as np
import matplotlib.pyplot as plt
y=np.arange(1,5)
plt.plot(y,"--")
plt.plot(y+1,"-.")
plt.plot(y+2,":")
plt.plot(y+3,"-")
plt.show()
7.4 样式字符串
c颜色,x点类型,–线类型
import numpy as np
import matplotlib.pyplot as plt
y=np.arange(1,5)
plt.plot(y,"cx--")
plt.plot(y+1,"mo-.")
plt.plot(y+2,"kp:")
plt.plot(y+3,"-")
plt.show()
8 面向对象和Matlab Style
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(0,10,1)
y=np.random.randn(len(x))
plt.plot(x,y)
plt.title('pyplot')
plt.show()
#pylab
from pylab import *
x=arange(0,10,1)
y=randn(len(x))
plot(x,y)
title('random numbers')
show()
#Object Oriented
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(0,10,1)
y=np.random.randn(len(x))
fig=plt.figure()
ax=fig.add_subplot(111)
l,=plt.plot(x,y)
t=ax.set_title('object oriented')
plt.show()
9 子图
面向对象方式
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1,100)
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax1.plot(x,x)
ax2 = fig.add_subplot(222)
ax2.plot(x,-x)
ax3 = fig.add_subplot(223)
ax3.plot(x,np.sin(x))
ax4 = fig.add_subplot(224)
ax4.plot(x,np.cos(x))
plt.show()
调用函数
x=np.arange(1,100)
plt.subplot(221)
plt.plot(x,x)
plt.subplot(222)
plt.plot(x,-x)
plt.subplot(223)
plt.plot(x,x*x)
plt.subplot(224)
plt.plot(x,np.log(x))
plt.show()
10 多图
import matplotlib.pyplot as plt
fig1=plt.figure()
ax1=fig1.add_subplot(111)
ax1.plot([1,2,3],[3,2,1])
fig2=plt.figure()
ax2=fig2.add_subplot(111)
ax2.plot([1,2,3],[1,2,3])
plt.show()
11 绘制网格
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
# # x = np.arange(1,5)
# # plt.plot(x,x**2)
# # plt.grid(color = "r",linewidth = "2",linestyle = "--")
# # plt.show()
#面向对象绘制网格方式
x = np.arange(1,10,1)
fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot(x,x**2)
ax.grid(color="g")
plt.show()
12 添加图例
import matplotlib.pyplot as plt
import numpy as np
**plt方法中,loc表示图例位置,ncol表示图例分成几列**
#plt第一种方法
x = np.arange(1,11,1)
# plt.plot(x,x*2,label = "Normal")
# plt.plot(x,x*3,label = "Fast")
# plt.plot(x,x*4,label = "Faster")
#
# #loc控制图例的位置
# plt.legend(loc=0,ncol=3) #loc=0 自适应,ncol控制图例分层几列
# plt.show()
#plt第二种方法
# plt.plot(x,x*2)
# plt.plot(x,x*3)
# plt.plot(x,x*4)
#
# #loc控制图例的位置
# plt.legend(["Normal","Fast","Faster"]) #loc=0 自适应,ncol控制图例分层几列
# plt.show()
#面向对象的方式
# fig = plt.figure()
# ax = fig.add_subplot(111)
# l,= plt.plot(x,x)
# ax.legend(["ax lengend"])
# plt.show()
# fig = plt.figure()
# ax = fig.add_subplot(111)
# l,= plt.plot(x,x)
# l.set_label("label via method")
# ax.legend()
# plt.show()
fig = plt.figure()
ax = fig.add_subplot(111)
l,= plt.plot(x,x,label = "Inline label")
ax.legend()
plt.show()
13 坐标轴
13.1 坐标轴范围
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus']=False
x = np.arange(-10,11,1)
plt.plot(x,x**2,label="二次函数")
plt.grid(color="r",linewidth=2,linestyle="--")
plt.legend(loc=0,ncol=1)
plt.axis([-5,5,20,60])
plt.show()
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus']=False
x = np.arange(-10,11,1)
plt.plot(x,x**2,label="二次函数")
plt.grid(color="r",linewidth=2,linestyle="--")
plt.legend(loc=0,ncol=1)
plt.xlim([-5,5])
plt.ylim([0,60])
plt.show()
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus']=False
x = np.arange(-10,11,1)
plt.plot(x,x**2,label="二次函数")
plt.grid(color="r",linewidth=2,linestyle="--")
plt.legend(loc=0,ncol=1)
# plt.axis([-5,5,20,60])
# plt.xlim([-5,5])
# plt.ylim([0,60])
# plt.xlim(xmin=-5,xmax=5)
plt.xlim(xmin=-5)
plt.show()
13.2 坐标轴刻度
指定坐标轴分成几块
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1,11,1)
plt.plot(x,x)
#plt.gac()为面向对象方式,无法交互
# ax = plt.gca() #获取当前坐标轴
# ax.locator_params("x",nbins=10) #不指定则表示默认x,y同步调整
#交互需使用plt自带函数
plt.locator_params("y",nbins=10)
plt.locator_params("x",nbins=10)
plt.show()
时间序列作图
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import datetime
fig = plt.figure()
start = datetime.datetime(2015,1,1)
stop = datetime.datetime(2016,1,1)
delta = datetime.timedelta(days=1)
dates = mpl.dates.drange(start,stop,delta)
y = np.random.rand(len(dates))
ax = plt.gca()
ax.plot_date(dates,y,linestyle = "-",marker = "")
date_format = mpl.dates.DateFormatter("%Y-%m") #调整时间格式
ax.xaxis.set_major_formatter(date_format)
plt.show()
加入自适应fig.autofmt_xdate()
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import datetime
fig = plt.figure()
start = datetime.datetime(2015,1,1)
stop = datetime.datetime(2016,1,1)
delta = datetime.timedelta(days=1)
dates = mpl.dates.drange(start,stop,delta)
y = np.random.rand(len(dates))
ax = plt.gca()
ax.plot_date(dates,y,linestyle = "-",marker = "")
date_format = mpl.dates.DateFormatter("%Y-%m")
ax.xaxis.set_major_formatter(date_format)
fig.autofmt_xdate() #自适应
plt.show()
13.3 添加坐标轴
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
x = np.arange(2,20,1)
y1 = x**2
y2 = np.log(x)
# plt.plot(x,y1)
# plt.twinx() #添加坐标轴
# plt.plot(x,y2,c = "r")
#
#
# plt.show()
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x,y1)
ax1.set_ylabel("Y1")
ax2 = ax1.twinx()
ax2.plot(x,y2,"r")
ax2.set_ylabel("Y2")
ax1.set_xlabel("Compare Y1 and Y2")
plt.show()
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
x = np.arange(2,20,1)
y1 = x**2
y2 = np.log(x)
plt.plot(y1,x)
plt.twiny()
plt.plot(y2,x,c="r")
plt.show()
14 注释
plt.annotate添加注释,xy表示箭头底部坐标位置,xytext表示文字坐标位置(箭头随之变化)
其中有arrowprops属性,headlenth和headwidth表示箭头长度和宽度,width表示箭身宽度
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
x = np.arange(-10,11,1)
y = x**2
plt.plot(x,y)
plt.annotate("this is the bottom",xy=(0,5),xytext = (0,30),
arrowprops=dict(facecolor="r",headlength=10,headwidth=10,width=5))
plt.show()
15 文字
plt.text(x,y,char) x,y文字的位置,family字体样式,size字体大小,style是否斜体,weight粗细,bbox文字上加不加框
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
x = np.arange(-10,11,1)
y = x**2
plt.plot(x,y)
plt.text(-3,40,"function y = x^2",family ="serif",color="g",size=20,style= "italic",weight=0)
plt.text(-2,20,"function y = x^2",family = "fantasy",
color"r",size=20,style="normal",weight=1000,
bbox=dict(facecolor="r",alpha=0.2))
plt.show()
16 公式
r表示不转义
具体公式实现需官网查询
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim([1,7])
ax.set_ylim([1,5])
ax.text(2,4,r"$\alpha_i \beta_j \pi \lambda \omega $",size=25)
ax.text(4,4,r"$\sin(0) = \cos(\frac{\pi}{2}) $",size=25)
ax.text(2,2,r"$\lim_{x \rightarrow y}\frac{1}{x^3} $",size=25)
ax.text(4,2,r"$\sqrt[4]{x} = \sqrt[2]{y} $",size=25)
plt.show()
17 填充
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
x = np.linspace(0,5*np.pi,1000)
y1 = np.sin(x)
y2 = np.sin(2*x)
plt.fill(x,y1,"b",alpha=0.3)
plt.fill(x,y2,"r",alpha=0.3)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
x = np.linspace(0,5*np.pi,100)
y1 = np.sin(x)
y2 = np.sin(2*x)
fig = plt.figure()
ax = plt.gca()
ax.plot(x,y1,color="r")
ax.plot(x,y2,color="b")
ax.fill_between(x,y1,y2,where=y1>y2,facecolor="yellow",interpolate=True)
ax.fill_between(x,y1,y2,where=y1<y2,facecolor="green",interpolate=True)
plt.show()
18 形状
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.patches as mpatches
fig,ax = plt.subplots()
xy1= np.array([0.2,0.2])
xy2 = np.array([0.2,0.8])
xy3 = np.array([0.8,0.2])
xy4 = np.array([0.8,0.8])
circle = mpatches.Circle(xy1,0.1)
ax.add_patch(circle)
# plt.axis("equal")
rect = mpatches.Rectangle(xy2,0.2,0.1,color="r")
ax.add_patch(rect)
polygon = mpatches.RegularPolygon(xy3,5,0.1,color = "green")
ax.add_patch(polygon)
ellipse = mpatches.Ellipse(xy4,0.4,0.2,color="y")
ax.add_patch(ellipse)
plt.show()
19 样式和美化
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
plt.style.use("ggplot")
fig,axes = plt.subplots(ncols=2,nrows=2)
ax1,ax2,ax3,ax4 = axes.ravel()
x,y = np.random.normal(size=(2,100))
ax1.plot(x,y,"o")
x = np.arange(0,10)
y = np.arange(0,10)
ncolors = len(plt.rcParams["axes.prop_cycle"]) #颜色的循环
shift = np.linspace(0,10,ncolors)
for s in shift:
ax2.plot(x,y+s,"-")
x = np.arange(5)
y1,y2,y3 = np.random.randint(1,25,size = (3,5))
width = 0.25
ax3.bar(x,y1,width)
ax3.bar(x+width,y2,width)
ax3.bar(x+2*width,y2,width)
for color in ["r","g","b","y","m"]:
xy = np.random.normal(size=2)
ax4.add_patch (plt.Circle(xy,radius=0.3,color=color))
ax4.axis("equal")
plt.show()
20 极坐标
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
r = np.arange(1,6,1)
theta = [0,np.pi/2,np.pi,3*np.pi/2,2*np.pi]
ax = plt.subplot(111,projection = "polar")
ax.plot(theta,r,color="r",linewidth =3)
ax.grid(True)
plt.show()