python+matplotlib练习

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基础环境:
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在线教程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值