【Python数据可视化分析】学习笔记

这些天一直在跟着b站上的Python数据可视化分析 matplotlib教程自学数据可视化相关基础知识(这位老师讲得挺好懂的,对新手学习很友好,感兴趣的小伙伴可以自行进入链接),搬运了一些自己在学习过程中编写的代码(主要是跟随教程),以防本地保存的内容丢失。

(以下所有的代码可以自行复制到本地,有注释的取消掉注释稍作调整即可运行)

一、数据可视化课程及numpy简介

# import matplotlib.pyplot as plt
# plt.plot([1,2,3],[3,2,1])
# plt.show()

# ndarray的创建方式
import numpy as np

# 方式1:从python的基础数据对象转化
# a = [1,2,3,4]
# x1 = np.array(a)
# print(type(x1))
# 方式2:通过numpy内生的函数生成
# x = np.arange(11)
# print(x)
# 方式3:从硬盘(文件)读取数据
# x = np.loadtxt('文件名',delimiter=',',skiprows=1,usecols=(1,4,6),unpack=False)

# 函数
# c = np.random.randint(1,100,10)
# print(c)
# print(np.min(c)) # print(c.min()) 其他函数同理
# print(np.max(c))
# print(np.mean(c))

二、散点图

import numpy as np
import matplotlib.pyplot as plt

# 身高&体重
height = [161,170,182,175,173,165]
weight = [50,58,80,70,69,55]

N = 1000

# 无相关
# height = np.random.randn(N)
# weight = np.random.randn(N)

# 正相关
# height = np.random.randn(N)
# weight = height+np.random.randn(N)*0.5

# 负相关
# height = np.random.randn(N)
# weight = -height+np.random.randn(N)*0.5

# 颜色:c 点大小:s 透明度:alpha 点形状:marker

# plt.scatter(height,weight,s=100,c='g',marker='.',alpha=0.5)
# plt.show()

三、折线图

import numpy as np
import matplotlib.pyplot as plt

# x = np.linspace(-10,10,100)
# y = x**2
#
# plt.plot(x,y,c='g')
# plt.show()

# 显示日期
# import matplotlib.dates as mdates
# date,open,close=np.loadtxt('',delimiter=',',converters={0:mdates.datestr2num('%m/%d/%Y')},skiprows=1,usecols={0,1,4},unpack=True)
# plt.plot_date(date,open,linestyle='-')
# plt.show()

四、条形图

import numpy as np
import matplotlib.pyplot as plt

N = 5
y = [20,10,30,25,15]
index = np.arange(N)
plt.bar(x=index,height=y,color='green',width=0.5)
# plt.barh(y=index,width=y,color='green',height=0.5)
plt.show()

# ***并列和层叠的方式

五、直方图

import numpy as np
import matplotlib.pyplot as plt

mu = 100
sigma = 20
x = mu + sigma * np.random.randn(2000)

plt.hist(x,bins=10,density=True,edgecolor='black')
plt.show()

# 双变量直方分布图
# k1 = np.random.randn(1000)+2
# k2 = np.random.randn(1000)+3
# plt.hist2d(k1,k2,bins=10)
# plt.show()

六、饼状图

import numpy as np
import matplotlib.pyplot as plt

labels = 'A','B','C','D'
fracs = [15,30,45,10]
explode = [0,0.06,0,0]
plt.pie(x=fracs,labels=labels,autopct='%.0f%%',explode=explode,shadow=True)
plt.show()

七、箱形图

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(100)
data = np.random.normal(size=(1000,4),loc=0,scale=1)
labels = ['A','B','C','D']
plt.boxplot(data,labels=labels,sym='o',whis=1.5)
plt.show()

八、颜色和样式

import numpy as np
import matplotlib.pyplot as plt

y = np.arange(1,5)
plt.plot(y,color='g')
# 灰色阴影
plt.plot(y+1,color='0.5')
# html 十六进制
plt.plot(y+2,color='#FF00FF')
# RGB元组
plt.plot(y+3,color=(0.1,0.2,0.3))
plt.show()

# 点、线样式 点:marker 线:四种 {-- -. : -}

# 样式字符串(好用)
# plt.plot(y,'cx--')

九、面向对象

import numpy as np
import matplotlib.pyplot as plt

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()

十、子图 subplot

# Matplotlib对象简介
# FigureCanvas/Figure/Axes
import numpy as np
import matplotlib.pyplot as plt

# 面向对象
# x = np.arange(1,100)
# fig = plt.figure()
# axl = fig.add_subplot(221)
# axl.plot(x,x)
# axl = fig.add_subplot(222)
# axl.plot(x,-x)
# axl = fig.add_subplot(223)
# axl.plot(x,x*x)
# axl = fig.add_subplot(224)
# axl.plot(x,np.log(x))
# plt.show()

# 交互式
x = np.arange(1,100)
plt.subplot(211)
plt.plot(x,x)
plt.show()

十一、多图 figure

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()

十二、网格

import numpy as np
import matplotlib.pyplot as plt

# y = np.arange(0,5)
# plt.plot(y,y*2)
# plt.grid(True,color='b',linestyle='--')
# plt.show()

x = np.arange(0,10,1)
fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot(x,x*2)
ax.grid()
plt.show()

十三、图例 legend

import numpy as np
import matplotlib.pyplot as 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')
# plt.legend(ncol=1)

fig = plt.figure()
ax=fig.add_subplot(111)
l, =plt.plot(x,x)
ax.legend(['ax_legend'])
plt.show()

十四、坐标轴范围

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-10,11,1)
plt.plot(x,x*x)
plt.axis([-10,10,0,60]) # xlim()/ylim()
plt.show()

十五、坐标轴刻度

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import datetime

# x = np.arange(1,11,1)
#
# plt.plot(x,x)
#
# ax = plt.gca()
#
# ax.locator_params('x',nbins=10)

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()

十六、添加坐标轴

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

x = np.arange(2,20,1)
y1 = x*x
y2 = np.log(x)

# 交互式
# plt.plot(x,y1)
# plt.twinx()
# plt.plot(x,y2,'r')

# 面向对象
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')

plt.show()

十七、注释

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-10,11,1)
y = x*x
plt.plot(x,y)
plt.annotate('this is the bottom',xy=(0,1),xytext=(0,20),
             arrowprops=dict(facecolor='g',headlength=10,headwidth=20,width=10))

plt.show()

十八、文字

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-10,11,1)
y = x*x
plt.plot(x,y)
plt.text(0,40,'func')
# 可以调整的参数: family size color style weight
plt.show()

十九、Tex公式

import numpy as np
import matplotlib.pyplot as plt

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 $",size=20)
ax.text(4,4,r"$ \sin(0)=\cos(\frac{\pi}{2}) $",size=20)
ax.text(2,2,r"$ \lim_{x \rightarrow y} \frac{1}{x^3} $",size=20)
ax.text(4,2,r"$ \sqrt[4]{x}=\sqrt{y} $",size=20)
plt.show()

二十、区域填充

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,5*np.pi,100)
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)

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,facecolors='yellow',interpolate=True)
ax.fill_between(x,y1,y2,where=y1<y2,facecolors='green',interpolate=True)
ax.grid()
plt.show()


2020.7.31 更新 (还差一些就学完基础了~)


二十一、形状

import numpy as np
import matplotlib.pyplot as plt
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)
rect = mpatches.Rectangle(xy2,0.2,0.1,color='r')
ax.add_patch(rect)
polygon = mpatches.RegularPolygon(xy3,5,0.1,color='g')
ax.add_patch(polygon)
ellipse = mpatches.Ellipse(xy4,0.4,0.2,color='y')
ax.add_patch(ellipse)

plt.axis('equal')
plt.grid()
plt.show()

二十二、样式 美化

import numpy as np
import matplotlib.pyplot as plt
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)
rect = mpatches.Rectangle(xy2,0.2,0.1,color='r')
ax.add_patch(rect)
polygon = mpatches.RegularPolygon(xy3,5,0.1,color='g')
ax.add_patch(polygon)
ellipse = mpatches.Ellipse(xy4,0.4,0.2,color='y')
ax.add_patch(ellipse)

plt.axis('equal')
plt.grid()
plt.show()

二十三、极坐标

import numpy as np
import matplotlib.pyplot as plt

# r = np.arange(1,6,1)

r = np.empty(5)
r.fill(5)

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()

(课程剩下的部分晚点继续补充,正在充电中)

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值