Matplotlib





一、绘图参数

1. 图数量

单图

x = np.linspace(-1, 1, 50)
y = x ** 2

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

多线

x = np.linspace(-1, 1, 50)
y1 = x ** 2
y2 = 2 * x + 1

# 在同一个figure中plot多条曲线
plt.plot(x, y2)
plt.plot(x, y1)

plt.show()

多图

x = np.linspace(-1, 1, 50)
y1 = x ** 2
y2 = 2 * x + 1

# 创建画布
plt.figure()
plt.plot(x, y1)
# 创建画布。设置画布参数
plt.figure(num=3, figsize=(8, 5))
plt.plot(x, y2)

plt.show()

子图

# 方法一,按划分的网格放置子图
plt.figure()
plt.subplot(2, 1, 1)
plt.plot([0, 1])
plt.subplot(2, 3, 4)
plt.subplot(2, 3, 5)
plt.subplot(2, 3, 6)

# 方法二,可设置子图长宽
plt.figure()
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1)
ax1.plot([1, 2])
ax1.set_title("title")
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax2.plot()
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
ax3.plot()
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax4.plot()
ax5 = plt.subplot2grid((3, 3), (2, 1))
ax5.plot()

plt.show()

图中图

# 主图
plt.plot([0, 1])

# 子图
plt.axes([0.6, 0.2, 0.2, 0.2])
plt.plot([1, 0], 'g')
plt.xlabel('x')

plt.show()

2. 线条

# 颜色
plt.plot([1, 2], color='red')

# 线宽
plt.plot([1, 2], linewidth=3)

# 线形
# '-' | '--' | '-.' | ':' | 'steps' 
plt.plot([1, 2], linestyle='--')

# 端点
# '+' | ',' | '.' | '1' | '2' | '3' | '4'
plt.plot([1, 2], marker='+')

# 透明度
plt.plot([1, 2], alpha=0.6)

3. 文本

标题

plt.plot([0, 1])

# 标题
plt.title(r"$This\ is\ Title$")

plt.show()

标签

plt.plot([0, 1])

# 标签
plt.xlabel("X")
plt.ylabel("Y")

plt.show()

图例

# 图例
p1, = plt.plot([0, 1], label='up')
p2, = plt.plot([0, 2], color='red', label='down')
plt.legend(handles=[p1, p2], labels=['a', 'b'], loc='best')

plt.show()

标注

# 主图
x = np.linspace(-1, 5, 50)
y = 2 * x + 1
plt.plot(x, y)

# 标注线
x0 = 1
y0 = 2 * x0 + 1
plt.plot([x0, x0], [y0, -1])

# 文本标注
plt.text(-1, 4, r"$This\ is\ some\ text$")

# 箭头标注
plt.annotate(r"$2x+1=%s$" % y0,
             xy=(x0, y0), xycoords='data', xytext=(+30, -30),
             textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle='->',
                             connectionstyle='arc3, rad=0.3'))

plt.show()

4. 坐标轴

网格

plt.plot([0, 1])

# 网格
plt.grid(True)
# 水平线
plt.axhline(1, color='r')
plt.axvline(1, color='b')

plt.show()

坐标范围

plt.plot([0, 1])

# 坐标范围
plt.xlim((-1, 1))
plt.ylim((-1, 1))

plt.show()

坐标刻度

plt.plot([0, 1])

# 坐标刻度
plt.xticks(np.linspace(0, 1, 5))
plt.yticks([0, 0.5, 1], [r"$bad$", r"$normal$", r"$good$"])

plt.show()

数学刻度

y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))

plt.plot(x, y)

# 数学刻度
plt.yscale('linear')
# plt.yscale('log')
# plt.yscale('symlog', linthreshy=0.05)
# plt.yscale('logit')

plt.show()

坐标背景色

plt.plot([0, 1])

# 坐标背景色
ax = plt.gca()
for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(12)
    label.set_bbox(dict(facecolor='green',
                        edgecolor='red',
                        alpha=0.7))

plt.show()

坐标轴隐藏

plt.plot([0, 1])

# 坐标轴隐藏
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

plt.show()

坐标轴移动

plt.plot([0, 1])

# 坐标轴隐藏
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

# 坐标轴移动
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 1))
ax.spines['left'].set_position(('data', 1))

plt.show()

多坐标轴

# 多坐标轴
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot([0, 1], 'g-')
ax2.plot([1, 0], 'b-')

ax1.set_xlabel("X")
ax1.set_ylabel("Y1", color='g')
ax2.set_ylabel("Y2", color='b')

plt.show()




二、各种图

1. 散点图

DataFrame

# DataFrame
df = pd.DataFrame(np.random.rand(50, 4), columns=['a', 'b', 'c', 'd'])

# 散点图
df.plot.scatter(x='a', y='b')
# 根据c值设置颜色
df.plot.scatter(x='a', y='b', c='c', s=50)
# 根据c值设置大小
df.plot.scatter(x='a', y='b', s=df['c'] * 200)
# 多组散点
ax = df.plot.scatter(x='a', y='b', color='DarkBlue', label='Group 1')
df.plot.scatter(x='c', y='d', color='DarkGreen', label='Group 2', ax=ax)

plt.show()

Series

n = 1024
x = np.random.normal(0, 1, n)
y = np.random.normal(0, 1, n)

# color map
T = np.arctan2(y, x)

# 散点图
plt.scatter(x, y, s=75, c=T, alpha=0.5)
plt.xlim((-1.5, 1.5))
plt.ylim((-1.5, 1.5))

plt.show()

2. 条形图

DataFrame

df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])

# 条形图
df.iloc[5].plot.bar()
# 多组条形
df.plot.bar()
# 堆叠
df.plot.bar(stacked=True)
# 水平方向
df.plot.barh(stacked=True)

plt.show()

Series

n = 12
x = np.arange(n)
y1 = (1 - x / float(n) * np.random.uniform(0.5, 1, n))
y2 = (1 - x / float(n) * np.random.uniform(0.5, 1, n))

# 条形图
plt.bar(x, +y1, facecolor='#9999ff', edgecolor='white')
plt.bar(x, -y1, facecolor='#ff9999', edgecolor='white')

plt.xlim((-0.5, n))
plt.ylim((-1.5, 1.5))
plt.xticks(())
plt.yticks(())

# 数值显示
Y1 = zip(x, y1)
Y2 = zip(x, y2)
for x, y in Y1:
    plt.text(x, y + 0.05, '%.2f' % y, ha='center', va='bottom')
for x, y in Y2:
    plt.text(x, - y - 0.05, '%.2f' % y, ha='center', va='top')

plt.show()

3. 直方图

DataFrame

df = pd.DataFrame({'a': np.random.randn(1000) + 1, 'b': np.random.randn(1000),
                   'c': np.random.randn(1000) - 1}, columns=['a', 'b', 'c'])

# 直方图
df.plot.hist(alpha=0.5)
# 堆叠
df.plot.hist(stacked=True)
# 条数
df.plot.hist(bins=20)
# 水平方向
df['a'].plot.hist(orientation='horizontal')
# 累计直方图
df['a'].plot.hist(cumulative=True)
# 子图
df.diff().hist(bins=50)

plt.show()

4. 箱线图

DataFrame

df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])

# 箱线图
df.plot.box()
# 箱线颜色
color = {'boxes': 'DarkGreen', 'whiskers': 'DarkOrange',
         'medians': 'DarkBlue', 'caps': 'Gray'}
df.plot.box(color=color)
# 异常点
df.plot.box(sym='r+')
# 水平方向
df.plot.box(vert=False)
# 绘图位置
df.plot.box(positions=[1, 4, 5, 6, 8])

plt.show()

5. 面积图

DataFrame

df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])

# 面积图
df.plot.area(stacked=False)

plt.show()

6. 饼状图

DataFrame

df = pd.DataFrame(3 * np.random.rand(4, 2),
                  index=['a', 'b', 'c', 'd'], columns=['x', 'y'])

# 多组饼状图
df.plot.pie(subplots=True, figsize=(8, 4))

plt.show()

Series

series = pd.Series(3 * np.random.rand(4),
                   index=['a', 'b', 'c', 'd'], name='series')

# 饼状图
series.plot.pie(labels=['AA', 'BB', 'CC', 'DD'], colors=['r', 'g', 'b', 'c'],
                autopct='%.2f', fontsize=20, figsize=(6, 6))

plt.show()

7. 等高线图

Series

def f(x, y):
    return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
    

n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)

X, Y = np.meshgrid(x, y)
# 颜色
plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot)
# 加线
C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidths=0.5)

# 等高线图
plt.clabel(C, inline=True, fontsize=10)

plt.show()
1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合;、下 4载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合;、下载 4使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合;、下载 4使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值