Python可视化分析—matplotlib

1.绘制直线图:

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 4)
print(x)

plt.plot(x, x * (-0.5), color="blue", linestyle="-",  label="y = x * (-0.5)", linewidth=2, marker="o")
plt.plot(x, x * 1.5, color="green",   linestyle="--", label="y = x * 1.5", linewidth=2, marker="*")  # g--表示绿色虚线
plt.plot(x, x * 3.0, color="orange",  linestyle=":",  label="y = x * 3.0", linewidth=2, marker="+")
plt.plot(x, x * 3.5, color="magenta", linestyle="-.", label="y = x * 3.5", linewidth=2, marker="D")

plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False    # 用来正常显示负号

plt.xlabel("输出值")
plt.ylabel("输入值")
plt.title(u"直线图")

plt.legend()
plt.show()

结果为:
在这里插入图片描述

2.绘制心形

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-8, 8, 1024)  # 输出的范围为(-8, 8)

y1 = 0.618 * np.abs(x) - 0.8 * np.sqrt(64 - x ** 2)  # 左部分
y2 = 0.618 * np.abs(x) + 0.8 * np.sqrt(64 - x ** 2)  # 右部分

plt.plot(x, y1, color="r")
plt.plot(x, y2, color="r")

plt.show()

在这里插入图片描述

3.绘制散点图

3.1.绘制不同大小和颜色的散点图

np.random.randn(d0, d1, …, dn):从标准正态分布中返回一个或多个样本值
np.random.rand(d0, d1, …, dn):产生随机样本,并且数字位于[0, 1]上

import numpy as np
import matplotlib.pyplot as plt

x = np.random.randn(200)
y = np.random.randn(200)
size = 50 * np.random.randn(200)  # Randomly assigned size
colors = np.random.rand(200)      # Randomly assign colors

print(x[:10])  # View the output
print(y[:10])

plt.scatter(x, y, s=size, c=colors)

plt.show()

在这里插入图片描述

3.2.绘制不同类型的散点图
import numpy as np
import matplotlib.pyplot as plt

x = np.random.rand(90, 2)  # 随机产生90个二维数组,分别对应90个点
print(x)

# numpy中的ones()用于构造全1矩阵
label = list(np.ones(40)) + list(2 * np.ones(30)) + list(3 * np.ones(20))
                                            # 类标 label 为1、2、3

label = np.array(label)
print(label)
print(type(label))
idx1 = np.where(label == 1)
idx2 = np.where(label == 2)
idx3 = np.where(label == 3)

# 绘图参数:x值、y值、点样式、颜色、类标、粗细
p1 = plt.scatter(x[idx1, 0], x[idx1, 1], marker='x', color='r', label='1', s=40)
p2 = plt.scatter(x[idx2, 0], x[idx2, 1], marker='+', color='b', label='2', s=30)
p3 = plt.scatter(x[idx3, 0], x[idx3, 1], marker='o', color='c', label='3', s=20)

plt.legend(loc='upper right')
plt.show()

在这里插入图片描述

4.绘制柱状图

栗子1:

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randint(0, 100, 4)  # 随机产生4个整数(0~100)
print(data)

ind = np.arange(4)  # 4个用户
print(ind)

width = 0.35   # 设置宽度
x = ['UserA', 'UserB', 'UserC', 'UserD']
plt.bar(ind, data, width, color='green', label='Data')
plt.xlabel("Username")
plt.ylabel("consumption")
plt.title("compare four user monthly consumption data")
plt.xticks(ind+width/2, x, rotation=40)  #  ind+width/2 表示的是横轴标签的位置  rotation旋转40°
plt.legend()
plt.show()

在这里插入图片描述
栗子2:

import numpy as np
import matplotlib.pyplot as plt

num = np.array([1342, 6092, 4237, 8291])    # 数量
ratio = np.array([0.75, 0.76, 0.72, 0.75])  # 男性占比
men = num * ratio
women = num * (1-ratio)
x = [u'学习', u'旅游', u'看剧', u'聊天']
plt.rcParams['font.sans-serif'] = ['SimHei']
# plt.rc('font', family='SimHei', size=13)   # 中文字体

width = 0.5
idx = np.arange(4)
plt.bar(idx, men, width, color='purple', label=u'男性用户')
plt.bar(idx, women, width, bottom=men, color='orange', label=u'女性用户')
plt.xticks(idx, x, rotation=40)  # idx+width/2 表示的是横轴标签的位置  rotation旋转40°
plt.legend(loc='upper right')  # 将标签框放在右上方
plt.show()

结果为:
在这里插入图片描述

4.绘制饼状图

import matplotlib.pyplot as plt

# 每一块占的比例,总和为100
mm = [45, 30, 25]
n = mm[0] + mm[1] + mm[2]
a = (mm[0] * 1.0 * 100/n)
b = (mm[1] * 1.0 * 100/n)
c = (mm[2] * 1.0 * 100/n)

print(a, b, c, n)
fracs = [a, b, c]
explode = (0, 0, 0.08)  # 离开整体的距离
labels = 'A', 'B', 'C'
plt.pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90, colors=("c", "r", "y"))
plt.show()

在这里插入图片描述

5.绘制3D图形

5.1.绘制3D坐标系
import matplotlib.pyplot as plt          # 绘图用的模块
from mpl_toolkits.mplot3d import Axes3D  # 绘图3D坐标的函数
fig1 = plt.figure()                      # 创建一个绘图对象
ax = Axes3D(fig1)                        # 用这个绘图对象创建一个Axes对象
plt.show()                               # 显示模块中所有的绘图对象

在这里插入图片描述

5.2.绘制3D图

栗子1:

import matplotlib.pyplot as plt            # 绘图用的模块
from mpl_toolkits.mplot3d import Axes3D    # 绘图3D坐标的函数
import numpy as np

fig = plt.figure()                         # 创建一个绘图对象
ax = Axes3D(fig)                           # 用这个绘图对象创建一个Axes对象

X = np.arange(-2, 2, 0.25)                 # x轴,-2到2之间,间隔0.25
print(X)
Y = np.arange(-2, 2, 0.25)                 # y轴,-2到2之间,间隔0.25

X, Y = np.meshgrid(X, Y)                   # 用两个坐标轴上的点在平面上画格
R = np.sqrt(X ** 2 + Y ** 2)               # X 和 Y平方和的平方根
Z = np.sin(R)                              # 计算sin()函数,并作为Z坐标

# 绘制一个三维曲面f(x, y)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='gist_ncar')
# 给3个坐标轴注明属性
ax.set_xlabel('x_label', color='r')
ax.set_ylabel('y_label', color='g')
ax.set_zlabel('z_label', color='b')
plt.show()

在这里插入图片描述
栗子2:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 创建X、Y、Z坐标
X = [1, 1, 2, 2]
Y = [3, 4, 4, 3]
Z = [1, 100, 1, 1]
fig = plt.figure()
# 创建了一个Axes3D的子图放到figure画布里面
ax = Axes3D(fig)
ax.plot_trisurf(X, Y, Z)
plt.show()

在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值