Python可视化图表(numpy+matplotlib)

 

1. 柱状图

import numpy as np
import matplotlib.pyplot as plt

boy = np.random.randint(20,35,size = 6)
girl = np.random.randint(20,35,size = 6)

labels = ['G1','G2','G3','G4','G5','G5']
plt.figure(figsize=(9,6))
x = np.arange(6)

width = 0.3
plt.bar(x - width/2,boy,width = width)
plt.bar(x + width/2,girl,width = width)

plt.legend(['Boy','Girl'])
plt.xticks(x,labels,fontsize = 20)

# 放置文本 text
for i in range(6):
    s1 = boy[i]
    plt.text(x = i - 0.15,y = s1 + 1,s = s1,ha = 'center')
    s2 = girl[i]
    plt.text(x = i + 0.15,y = s2 + 1,s = s2,ha = 'center')
    
plt.ylim(0,40)

实现效果:

2. 极坐标图

2.1  线性极坐标图
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,4* np.pi,200)
y = np.linspace(0,2,200)

ax = plt.subplot(111,projection = 'polar',facecolor = 'lightgreen')
ax.plot(x,y)

# 设置
ax.set_rmax(3)

ax.set_rticks([0.5,1,1.5,2])
ax.grid(True)

实现效果:

2.2  条形极坐标
import numpy as np
import matplotlib.pyplot as plt

N = 8 # 分成8份(0 到 360)
x = np.linspace(0, 2 * np.pi, N, endpoint=False)

# 纵坐标
y = np.random.randint(3,15,size = N)

# 宽度,8个柱子沾满圆
width = np.pi / 4

# 颜色,0到1
colors = np.random.rand(8,3) # 随机生成颜色

# 创建极坐标
ax = plt.subplot(111,projection = 'polar') # polar表示极坐标

# 绘制条形图
plt.bar(x, y, width=width,color = colors)

实现效果:

3. 直方图

import numpy as np
import matplotlib.pyplot as plt

mu = 100 # 平均值
sigma = 15 # 标准差
# 10000个数据
x = np.random.normal(loc = mu,scale = 15,size = 10000)
fig, ax = plt.subplots()

# 描述统计性的数据
# 数据量比较大,通过绘制直方图,看出数据内部关系
# 将数据分成200份
# density=False 统计数字在某个范围内的次数
# density= True,概率
n, bins, patches = ax.hist(x, 10, density=False,rwidth=0.8) # 直方图

实现效果:

4. 箱型图

import numpy as np
import matplotlib.pyplot as plt
data=np.random.normal(size=(500,4)) # 正太分布

lables = ['A','B','C','D']
# 用Matplotlib画箱线图

# 黄色线,中位数
# 查看数据分布情况,看异常值
_ = plt.boxplot(data,1,'ro',labels=lables) # 红色的圆点是异常值

实现效果:

5. 散点图

import numpy as np
import matplotlib.pyplot as plt
data = np.random.randn(100,2)

s = np.random.randint(100,300,size = 100)
color = np.random.randn(100)

plt.scatter(data[:,0], # 横坐标
            data[:,1], # 纵坐标
            s = s, # 尺寸
            c = color, # 颜色
            alpha = 0.5) # 透明度

实现效果:

6. 饼图

import numpy as np
import matplotlib.pyplot as plt
# 解决中文字体乱码的问题
plt.rcParams['font.sans-serif']='STKaiti' 

labels =["五星","四星","三星","二星","一星"] # 标签
percent = [95,261,105,30,9] # 某市星级酒店数量

# 设置图片大小和分辨率
fig=plt.figure(figsize=(5,5), dpi=120)

# 偏移中心量,突出某一部分
# 0.1 表示 10%,自身高度的10%,相对值
explode = (0, 0, 0, 0.1, 0) 
# 绘制饼图:autopct显示百分比,这里保留一位小数;shadow控制是否显示阴影

_ = plt.pie(x = percent,labels=labels,autopct='%0.1f%%',
            explode = explode,shadow=True) # 数据 # 阴影,3D效果

实现效果:

7. 热力图

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

# 标签
vegetables = ["cucumber", "tomato", "lettuce", "asparagus","potato", "wheat", "barley"]
farmers = list('ABCDEFG')

# 创造数据,随机数
harvest = np.random.randn(7,7)*5 # 农民丰收数据

plt.rcParams['font.size'] = 18
plt.rcParams['font.weight'] = 'heavy'

plt.figure(figsize=(6,6))

# imshow,显示图片
im = plt.imshow(harvest,cmap = 'PuBu')# 因为数值,各不相同

# 绘制文本
for i in range(len(vegetables)):
    for j in range(len(farmers)):
        text = plt.text(j, i, round(harvest[i, j],1),
                       ha="center", va="center", color='r')

实现效果:

8. 蜘蛛图

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'STKaiti'
labels=np.array(["个人能力","IQ","服务意识","团队精神","解决问题能力","持续学习"])
y=[83, 61, 95, 67, 76, 88]

# 画图数据准备,角度、状态值
x = np.linspace(0, 2*np.pi, len(labels), endpoint=False)

y = np.concatenate([y,[y[0]]]) # 首尾相接
x = np.concatenate([x,[x[0]]]) # 增加
print(y)

# 用Matplotlib画蜘蛛图
fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111, polar=True)   

# o表示形状,圆形
# -实线
# o-属性连用
ax.plot(x, y, 'r*--', linewidth=2,markersize = 30) # 连线
ax.fill(x,y,alpha = 0.2)

# x = 3.14 ---> 180
# 标签显示,去掉一个
_ = ax.set_thetagrids(x[:-1] * 180/np.pi,
                  labels,
                  fontsize = 18)

实现效果:

9. 3D图形

9.1  线形图&散点图
import numpy as np
import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d.axes3d import Axes3D

x = np.linspace(0,60,300)
y = np.sin(x)
z = np.cos(x)

# fig = plt.figure(figsize=(9,6))
# a3 = Axes3D(fig) # 二维变成3D
# a3.plot(x,y,z)
plt.figure(figsize=(9,6))
a3 = plt.subplot(111,projection = '3d')
a3.plot(x,y,z) # 普通线形图
a3.set_xlabel('X')
a3.set_ylabel('Y')
a3.set_zlabel('Z')

# 散点图
x = np.random.randint(0,60,size = 20)
y = np.random.randn(20)
z = np.random.randn(20)
a3.scatter(x,y,z,color= 'red')
# 调整视图的角度
a3.view_init(elev = 20,azim=-30)

实现效果:

9.2  3D条形图
import numpy as np
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')

from mpl_toolkits.mplot3d.axes3d import Axes3D # 3D引擎
month = np.arange(1,5)
# 每个月 4周 每周都会产生数据
# 三个维度:月、周、销量
fig = plt.figure(figsize=(9,6))
ax3 = Axes3D(fig)

for m in month:
    # 每个月都要绘制条形图
    ax3.bar(np.arange(1,5), # 理解成横坐标
            np.random.randint(1,10,size = 4), # 纵坐标
            zs = m ,
            zdir = 'x',# 在哪个方向上,一排排排列
            alpha = 0.7,# alpha 透明度
            width = 0.5)
    
    
ax3.set_xlabel('月份',fontsize = 18,color = 'red')
ax3.set_xticks(month)
ax3.set_ylabel('周',fontsize = 18,color = 'red')
ax3.set_yticks([1,2,3,4])
ax3.set_zlabel('销量',fontsize = 18,color = 'green')

实现效果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值