python+matplotlib练习

这篇博客介绍了使用Python的matplotlib库进行基础绘图的练习,包括plot()函数的使用,如何在图表上添加文字(如xlabel(), ylabel(), title()),以及基本饼图和以时间为轴的图表的绘制。通过实例展示了matplotlib的功能,并提供了教程链接。" 122287659,5623579,Kotlin编程:类与对象详解,"['Kotlin', 'Android开发', '编程概念']

基础环境:
1.python34
2.matplotlib1.4.3
3.win32

matplotlib基础练习一 plot()

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()

效果
这里写图片描述

如上:若只赋予plot()一个参数,那么matplotlib会自动赋值给x轴,且从0开始,所以该图效果等同于:

plt.plot([0,1,2,3],[1,2,3,4])

例子:

plt.plot([0,1,2,3],[1,2,3,4],color='#254424',linestyle='dashed',label='line 1')
plt.plot([1,2,3],[1,4,9],'rs',label='line 2')

更多使用方法要查看帮助 : help(“matplotlib.pyplot.plot”)


matplotlib基础练习二 文字
在图标上增加文字,主要使用如下函数

  1. text() - add text at an arbitrary location to the Axes;matplotlib.axes.Axes.text() in the API.
  2. xlabel() - add an axis label to the x-axis;matplotlib.axes.Axes.set_xlabel() in the API.
  3. ylabel() - add an axis label to the y-axis;matplotlib.axes.Axes.set_ylabel() in the API.
  4. title() - add a title to the Axes; matplotlib.axes.Axes.set_title() in the API.
  5. figtext() - add text at an arbitrary location to the Figure; matplotlib.figure.Figure.text() in the API.
  6. suptitle() - add a title to the Figure; matplotlib.figure.Figure.suptitle() in the API.
  7. annotate() - add an annotation, with
    optional arrow, to the Axes ; matplotlib.axes.Axes.annotate() in the API.

例:

# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt

fig = plt.figure()
fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')

ax = fig.add_subplot(111)
fig.subplots_adjust(top=0.85)
ax.set_title('axes title')

ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')

ax.text(3, 8, 'boxed italics text in data coords', style='italic',
        bbox={'facecolor':'red', 'alpha':0.5, 'pad':10})

ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15)

ax.text(0.95, 0.01, 'colored text in axes coords',
        verticalalignment='bottom', horizontalalignment='right',
        transform=ax.transAxes,
        color='green', fontsize=15)


ax.plot([2], [1], 'o')
ax.annotate('annotate', xy=(2, 1), xytext=(3, 4),
            arrowprops=dict(facecolor='black', shrink=0.05))

ax.axis([0, 10, 0, 10])

plt.show()

效果如图:
这里写图片描述


matplotlib基础练习三 基本饼图

import matplotlib.pyplot as plt

labels = 'GreenApple', 'YellowApple', 'RedApple'
sizes = [40, 25, 35]
colors = ['yellowgreen', 'gold', '#ff2121',]
explode = (0, 0.1, 0) 


plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=90)

plt.axis('equal')

plt.show()

效果:
这里写图片描述


matplotlib基础练习四-以时间为轴的图表

目录结构: -date_demo.py -aaa
-aapl.csv
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.ticker as ticker

r = mlab.csv2rec('aaa/aapl.csv')
r.sort()
r = r[-30:]  # get the last 30 days

N = len(r)
ind = np.arange(N)  # the evenly spaced plot indices

def format_date(x, pos=None):
    thisind = np.clip(int(x+0.5), 0, N-1)
    return r.date[thisind].strftime('%Y-%m-%d')

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(ind, r.adj_close, 'o-')
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
fig.autofmt_xdate()

plt.show()

aapl.csv下载地址


matplotlib在线教程

### Python Matplotlib 练习题与教程 以下是有关 Python Matplotlib 的一些练习题和教程资源,帮助用户更好地掌握该工具。 #### 基础绘图入门 对于初学者来说,可以参考基础绘图的内容[^1]。这通常涉及简单的线条绘制、散点图以及基本的图形属性设置。例如: ```python import matplotlib.pyplot as plt # 创建数据 x = [1, 2, 3, 4, 5] y = [1, 4, 9, 16, 25] # 绘制折线图 plt.plot(x, y, label="Line", color='blue', marker='o') # 添加标题和标签 plt.title("Basic Line Plot") plt.xlabel("X-axis Label") plt.ylabel("Y-axis Label") # 显示图例 plt.legend() # 展示图像 plt.show() ``` 此代码片段展示了一个简单的一维数组之间的关系,并通过 `plot` 函数实现可视化[^4]。 #### 高级功能探索 如果想进一步学习高级功能,则可尝试使用补丁 (patches) 和路径 (path),这些模块允许创建自定义形状并对其进行变换处理[^2]。下面是一个具体实例: ```python import matplotlib.pyplot as plt from matplotlib.patches import Circle, PathPatch from matplotlib.path import Path import numpy as np fig, ax = plt.subplots() circle = Circle((0.5, 0.5), 0.2, edgecolor='black', facecolor='none') ax.add_patch(circle) vertices = [(0.2, 0.8), (0.8, 0.8), (0.5, 0.2)] codes = [Path.MOVETO, Path.LINETO, Path.CLOSEPOLY] path = Path(vertices, codes) patch = PathPatch(path, fill=False, lw=2, transform=ax.transData) ax.add_patch(patch) ax.set_xlim(0, 1) ax.set_ylim(0, 1) plt.axis('equal') plt.show() ``` 上述脚本演示了如何利用路径对象构建多边形区域,并将其添加到坐标轴上显示出来。 #### 动画制作实践 动画也是 Matplotlib 中非常有趣的一部分[^3]。这里提供一段用于生成动态更新图表的小程序作为示范: ```python import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation def update(frame): line.set_ydata(np.sin(x + frame / 10)) return line, fig, ax = plt.subplots() x = np.linspace(0, 2 * np.pi, 100) line, = ax.plot(x, np.sin(x)) ani = animation.FuncAnimation(fig, update, frames=np.arange(0, 20, 0.1), blit=True) plt.show() ``` 这段代码实现了正弦波随时间变化的效果,其中每一帧都调用了回调函数来重新计算曲线上的点位置。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值