Matplotlib基础

1152-张同学

发表文章数:21

首页 » 数据科学库 » 正文

Matplotlib基础

Matplotlib 是 Python 的绘图库。 它可与 NumPy 一起使用,提供了一种有效的 MatLab 开源替代方案。 它也可以和图形工具包一起使用。

1.散点图

import matplotlib.pyplot as plt
import numpy as np

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)
y = x + np.random.randn(N) * 0.5

plt.scatter(x, y)
plt.show()

fpath = r"D:/WinterIsComing/python/New_Wave/Machine_Learning/Numpy_basic/numpy课件及源码/4_素材文件和源代码/000001.csv"

open, close = np.loadtxt(fpath, delimiter=",", skiprows=1, usecols=(1, 4), unpack=True)

change = close - open
print(change.shape)

# 画出前一天与后一天涨幅的散点图,先取前241个值(去掉最后一天),再取后241个值(去掉第一天)
yesterday = change[:-1]
today = change[1:]

# 从散点图可以看出,前一天和后天的涨幅没有明显的相关性
# 散点图的外观调整
plt.scatter(yesterday, today, s=200, c="r", marker="<", alpha="0.5")
plt.show()

# 练习
"""
使用000001.SH数据,计算最高价和开盘价值差diff
绘出前后两天diff的散点图,研究是否有相关性
"""
fpath = r"D:/WinterIsComing/python/New_Wave/Machine_Learning/Numpy_basic/numpy课件及源码/4_素材文件和源代码/000001.csv"
open, high = np.loadtxt(fpath, delimiter=",", skiprows=1, usecols=(1, 2), unpack=True)
diff = high - open
print(diff)

yesterday = diff[:-1]
today = diff[1:]

plt.scatter(yesterday, today, s=300, c="r", marker="<", alpha="0.5")
plt.show()

2.折线图

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

# linspace:从-10到10,平均生成5份
x = np.linspace(-10, 10, 5)
y = x ** 2

plt.plot(x,y)
plt.show()

fpath = r"D:/WinterIsComing/python/New_Wave/Machine_Learning/Numpy_basic/numpy课件及源码/4_素材文件和源代码/000001.csv"

# converters={0: mdates.strpdate2num("%m%d%Y")},将第0列的日期转化为了date数据
date, open, close = np.loadtxt(fpath, delimiter=",", converters={0: mdates.bytespdate2num("%m/%d/%Y")}, skiprows=1,
                               usecols=(0, 1, 4), unpack=True)

# plt.plot(date, open)
plt.plot_date(date, open, linestyle="--", color="red", marker="<", alpha=0.5)
# plot_date用于专门绘制有一个坐标是时间的图形

# 绘制两条折线
plt.plot_date(date, close, linestyle="-", color="green", marker="o", alpha=0.5)
plt.show()

# 练习
"""
画出x值为[0,10]的正弦函数图像
读取0000001的open,high,low,close,并将他们画在一张图上
"""
x = np.random.randint(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.show()

fpath = r"D:/WinterIsComing/python/New_Wave/Machine_Learning/Numpy_basic/numpy课件及源码/4_素材文件和源代码/000001.csv"
date, open, high, low, close = np.loadtxt(fpath, delimiter=",", converters={0: mdates.bytespdate2num("%m/%d/%Y")},
                                          skiprows=1, usecols=(0, 1, 2, 3, 4), unpack=True)

plt.plot_date(date, open, linestyle="-", c="red")
plt.plot(date, high, linestyle="--", c="green")
plt.plot(date, low, linestyle="-", c="pink")
plt.plot(date, close, linestyle="--", c="blue")
plt.show()

3.条形图

import numpy as np
import matplotlib.pyplot as plt

N = 5
y = [20, 10, 30, 25, 15]
index = np.arange(N)
#
# x是条形图的横坐标
p1 = plt.bar(x=index, height=y, color="skyblue", width=0.5)


# orientation="horizontal" 横向显示柱状图
p1 = plt.bar(x=0, bottom=index, height=0.5, color="skyblue", width=y, orientation="horizontal")
plt.show()

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')
# index+bar_width,上海的bar在横坐标的基础上平移一个bar_width
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()

# 练习
"""
生成两组大小为5的数据
画出两组数组水平的条形图
采用并列和层叠两种方式
"""

index = np.arange(5)

sales_BJ = [52, 55, 63, 53, 77]
sales_SH = [44, 66, 55, 41, 65]

bar_width = 0.3
plt.bar(x=0, bottom=index, width=sales_BJ, height=bar_width, color="r", orientation="horizontal")
# plt.bar(x=0, bottom=index + bar_width, width=sales_SH, height=bar_width, color="g", orientation="horizontal")
plt.bar(x=sales_BJ, bottom=index, width=sales_SH, height=bar_width, color="g", orientation="horizontal")
plt.show()

4.直方图

import numpy as np
import matplotlib.pyplot as plt

mu = 100  # mean of distribution
sigma = 20  # standard deviation of distribution
x = mu + sigma * np.random.randn(20000)

# bins代表图形中直方的数量
# normed代表是否要对数据进行标准化
plt.hist(x, bins=100, color="green", normed=False)
plt.show()

# 双变量直方图
x = np.random.randn(1000) + 2
y = np.random.randn(1000) + 3

plt.hist2d(x, y, bins=40)
plt.show()

# 练习
"""
随机生成2000个数据,均值为10,方差为3
绘制两个直方图,bins分别为10和50,normed分别为true和false
"""
mu = 10  # mean of distribution
sigma = 3  # standard deviation of distribution
x = mu + sigma * np.random.randn(2000)

plt.hist(x, bins=10, normed=True)
plt.show()

"""
随机生成x和y,分别2000个,x均值为1,y均值为5
绘制2D直方图,bins为40个
"""
x = np.random.randn(2000) + 1
y = np.random.randn(2000) + 5

plt.hist2d(x, y, bins=40)
plt.show()

5.饼状图

import matplotlib.pyplot as plt
import numpy as np

labels = 'A', 'B', 'C', 'D'
fracs = [15, 30, 45, 10]
explode = [0, 0.05, 0, 0]

plt.axes(aspect=1)
plt.pie(x=fracs, labels=labels, autopct="%.0f%%", explode=explode, shadow=True)
plt.show()

# 练习
"""
绘制饼状图,突出显示SZ,百分比精确到小数点后1位,有阴影
"""
labels = 'SH', 'BJ', 'SZ', 'GD'
fracs = [20, 10, 30, 25]

plt.pie(x=fracs, labels=labels, autopct="%.1f%%", shadow=True)
plt.show()

6.箱形图

import matplotlib.pyplot as plt
import numpy as np

data = np.random.normal(size=1000, loc=0.0, scale=1.0)

plt.boxplot(data, sym="<", whis=10)
plt.show()

data = np.random.normal(size=(1000, 4), loc=0, scale=1)
labels = ["A", "B", "C", "D"]

plt.boxplot(data, labels=labels)
plt.show()
labels = ['A','B','C','D','E']
data = np.random.normal(size=(100, 5), loc=0, scale=1)
plt.boxplot(data, labels=labels, sym="o", whis=3)
plt.show()

7.颜色和样式

import matplotlib.pyplot as plt
import numpy as np

y = np.arange(1, 5)
plt.plot(y, color="g", marker="o", linestyle="--")

# 颜色、点形、线形
# 灰度,灰色,数字代表颜色的深浅
plt.plot(y + 1, color="0.5", marker="D", linestyle="-.")
# 十六进制
plt.plot(y + 2, color="#FF00FF", marker="^", linestyle=":")
# RGB
plt.plot(y + 3, color=(0, 0.2, 0.5), marker="p", linestyle="-")
plt.show()

plt.plot(y + 1, "cx--")
plt.plot(y + 2, "kp:")
plt.plot(y + 3, "mo--")
plt.show()

# 练习
"""
使用样式字符串绘制两条线
1.红色,实现,圆点
2.黄色,虚线,三角形点
"""

x = np.arange(10)
plt.plot(x, "ro-")
plt.plot(x+1, "y^:")
plt.show()

8.面向对象与Matlab Style

# 总结:实战中推荐,根据需求,综合使用pyplot和面向对象方式

# 1.pylab
from pylab import *

x = arange(0, 10, 1)
y = randn(len(x))

plot(x, y)
show()

# 2.plt方式
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)
y = np.random.randn(len(x))

plt.title("pyplot")
plt.plot(x, y)
plt.show()

# 3.面向对象方式
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)
y = np.random.randn(len(x))

# # plt.figure()生成一个画布对象
fig = plt.figure()

# 生成一个坐标轴对象
# 111表示一行、一列、第一个
ax = fig.add_subplot(111)
# # 221表示2行、2列,第一个
ax = fig.add_subplot(221)
ax = fig.add_subplot(222)
ax = fig.add_subplot(223)
ax = fig.add_subplot(224)
a, = plt.plot(x, y)
b, = plt.plot(x + 1, y + 1)
c, = plt.plot(x + 2, y + 2)
d, = plt.plot(x + 3, y + 3)
t = ax.set_title("object oriented")
plt.show()

# ax = fig.add_subplot(221)

# 练习:使用面向对象的方式绘制正弦函数图
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(-np.pi, np.pi, 100)
y = np.sin(x)
plt.plot(x, y)
t = ax.set_title("object oriented")
plt.show()

9.子图-subplot

import matplotlib.pyplot as plt
import numpy as np

"""
Matplotlab对象简介
1.FigureCanvas 画布
2.Figure 图
3.Axes 在Figure上生成的坐标轴


ax = fig.add_subplot(111)
返回Axes实例
参数一,子图总行数
参数二,子图总列数
参数三,子图位置
在Figure上添加Axes的常用方法
"""
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, x * x)

ax4 = fig.add_subplot(224)
ax4.plot(x, np.log(x))
plt.show()

# 通过plt画子图
x = np.arange(1, 100)
plt.subplot(221)
plt.plot(x, x)

plt.subplot(222)
plt.plot(x, x * x)

plt.subplot(223)
plt.plot(x, -x)

plt.subplot(224)
plt.plot(x, np.log(x))
plt.show()

# 练习:创建一个1*2的子图区域,并画不同图形
s = np.arange(100)
plt.subplot(121)
plt.plot(s, -s)

plt.subplot(122)
plt.plot(s, s * 2)
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()

fig3 = plt.figure()
ax3 = fig3.add_subplot(111)
ax3.plot([4, 5, 6], [6, 5, 4])

fig4 = plt.figure()
ax4 = fig4.add_subplot(111)
ax4.plot([4, 5, 6], [4, 5, 6])
plt.show()

11.网格

import matplotlib.pyplot as plt
import numpy as np

# 1.plt方式绘制网格
y = np.arange(1, 5)
plt.plot(y, y * 2)
# 使用网格
plt.grid(True)
# 变更网格颜色
plt.grid(color="r")
# 调整网格线条粗细
plt.grid(linewidth="0.5")
# 更改网格线形
plt.grid(linestyle="--")
plt.show()

# 2.面向对象的方式绘制网格
x = np.arange(10)
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, x * 2)
ax1.grid(color="green")
ax1.grid(linestyle="--")
ax1.grid(linewidth=1)
plt.show()

z = np.arange(12).reshape(3, 4)
plt.plot(z, z * 2)
plt.grid(color="g")
plt.grid(linestyle="--")
plt.grid(linewidth=1)
plt.show()

12.图例

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 11)
plt.plot(x, x * 2, label="Normal")
plt.plot(x, x * 3, label="Fast")
plt.plot(x, x * 4, label="Faster")

# loc:位置参数1为右上角,2为左上角,0为自适应
plt.legend(loc=0)

# 使图例扁平化显示
plt.legend(ncol=3)

# 直接在legend中也可以指定图例
plt.legend(["1", "2", "3"])

plt.show()

y = np.arange(10)
plt.plot(y, y)
plt.plot(y, y * 2)
plt.plot(y, y * 3)
plt.legend(["A", "B", "C"], ncol=3)
plt.show()

13.坐标轴范围

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-10, 11)

plt.plot(x, x * x)
# (-11.0, 11.0, -5.0, 105.0)x,y轴的最小及最大坐标
print(plt.axis())
# 调整坐标轴
plt.axis([-5, 5, 20, 60])

# 只调整x轴
plt.xlim(0, 10)
# 只调整y轴
plt.ylim(0, 100)

14.坐标轴刻度

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

x = np.arange(1, 11)
plt.plot(x, x)
# plt.gca获得当前的坐标图形
ax = plt.gca()
# ax.locator_params("y", nbins=5)
plt.locator_params('x', nbins=5)

plt.show()

# 日期格式的调整
s = pd.date_range(start="2015-01-01", periods=366, freq="D")
print(s)
y = np.random.rand(len(s))
print(y)
ax = plt.gca()
ax.plot_date(s, y, linestyle="-", marker="<")
plt.show()

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="<")
plt.show()

15.添加坐标轴

import matplotlib.pyplot as plt
import numpy as np

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

plt.plot(x, y1)
plt.twinx()
plt.plot(x, y2, "r")
plt.show()

plt.plot(y1, x)
plt.twiny()
plt.plot(y2, x, color="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")
ax1.set_xlabel("Compare Y1 and Y2")
plt.show()

未经允许不得转载:作者:1152-张同学, 转载或复制请以 超链接形式 并注明出处 拜师资源博客
原文地址:《Matplotlib基础》 发布于2020-09-13

分享到:
赞(0) 打赏

评论 抢沙发

评论前必须登录!

  注册



长按图片转发给朋友

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏

Vieu3.3主题
专业打造轻量级个人企业风格博客主题!专注于前端开发,全站响应式布局自适应模板。

登录

忘记密码 ?

您也可以使用第三方帐号快捷登录

Q Q 登 录
微 博 登 录