python学习笔记--5.绘图

这是在学习Python的时候做的笔记,有些时间了,大概是按照一本挺实用的入门书籍学的,我学习编程的思路一般是掌握基础的变量类型,语法-分支结构 函数调用 类创建 结构体定义,记录一些简单的实例,剩下的就是需要用什么百度现学。

对我来说python的优势是,没有类型要求,不用声明,没有指针,万能数组,库很强大。

python可以绘制多种多样并且很好看的图

# 单曲线
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from PIL import Image   # python自带PIL停止更新了 所以使用Pillow, 它是由PIL发展而来的
import pylab

pathsave = "F:\SOFTWARE\编程软件\python\\test.png"

# region一些基础的函数含义
# 绘制简单的图
x = np.linspace(0, 5, 50)
y_cos = np.cos(x)
y_sin = np.sin(x)
# 同一个上面绘制两条曲线
fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot(x, y_cos)
plt.plot(x, y_sin)
plt.xlabel('x')
plt.ylabel('y')
plt.title('title')
# 移动坐标轴
# 隐藏邮编和上边的轴
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
# 设置将坐标显示在下边和左边的轴上 并且设置两轴焦点的位置
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))  # 设置焦点在y轴的0处
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 2.5))  # 将y轴平移到x轴的2.5处
# 设置坐标轴的刻度和标签 也可以单独设置 并且不显示刻度 只显示标签
ax.set_xticks([-3, 0, 3, 5])
ax.set_xticklabels(['qw', 'er', 'ty', 'yu'])
plt.savefig(pathsave)

# 绘制分块图
# 2,2,1 2 3 4是四个 2,1,1 34 35 36另一种四个
plt.subplot(1, 2, 1)
plt.plot(x, y_cos, 'r--')
plt.title('cos')
plt.subplot(1, 2, 2)
plt.plot(x, y_sin, 'b-')
plt.title('sin')
plt.show()



# 使用matplotlib的示例:调整字体-设置刻度、坐标、colormap和colorbar等
# fig, axs = plt.subplot(2, 2, figsize=(15, 15)) # 设置创建的figure对象的大小

fig = plt.figure(figsize=(3, 3))  # 设置涂面大小
ax = fig.add_subplot(1, 1, 1, frameon=False)  # 增添画板
ax.set_xlim(-0.015, 1.515)  # 设置x轴范围
ax.set_ylim(-0.01, 1.01)  # 设置y轴范围
ax.set_xticks([0, 0.3, 0.4, 1.0, 1.5])  # 设置x轴刻度位置

# 增加0.35处的刻度,用于标注0.3和0.4处文本 避免重叠
ax.set_xticklabels([0.0, "", "", 1.0, 1.5])
ax.set_xticks([0.35], minor=True)  # minor 设置最小的刻度 还是所有
ax.set_xticklabels(["0.3 0.4"], minor=True)  # 也是设置文本位置的
# 不显示所有minor属性的线条
for line in ax.xaxis.get_minorticklines():
    line.set_visible(False)

ax.grid(True)  # 开启图形的刻度网格
plt.savefig(pathsave)
# endregion

# region 注释annotate用法
fig = plt.figure(figsize=(3, 3))  # 设置涂面大小
ax = fig.add_subplot(1, 1, 1, frameon=False)  # 增添画板
delta = 2.0
x = np.linspace(-10, 10, 100)  # 返回指定间隔的数组 100个数
y = np.sinc(x-delta)

plt.axvline(delta, ls="--", color="r")  # 设置颜色和线条
# 在使用annotate时,要考虑两个点的坐标:被注释的地方xy(x, y)和插入文本的地方xytext(x, y)
plt.annotate(r"$\delta$", xy=(delta+0.2, -0.2), color="r", size=15, xytext=(2, 0.8),
             arrowprops=dict(facecolor='black', shrink=0.05))  # arrowprops箭头属性
plt.plot(x, y)
plt.savefig(pathsave)
# endregion

# region 单曲线图例子
# 设置坐标轴数据
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
# Note that using plt.subplots below is equivalent to using
# fig = plt.figure() and then ax = fig.add_subplot(111)
fig, ax = plt.subplots()
ax.plot(t, s)
# plt.axis('off')  # 关闭坐标轴
# 设置坐标轴名称
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
       title='About as simple as it gets, folks')
ax.grid()
# path = "F:\SOFTWARE\编程软件\python\\test.png"
fig.savefig(path)
plt.show()
# endregionyayan

# region 双图带有样式的
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

plt.subplot(2, 1, 1)
plt.plot(x1, y1, 'o-')
plt.title('A tale of 2 subplots')
plt.ylabel('Damped oscillation')

plt.subplot(2, 1, 2)
plt.plot(x2, y2, '.-')
plt.xlabel('time (s)')
plt.ylabel('Undamped')
path2 = "F:\SOFTWARE\编程软件\python\\test2.png"
plt.show()
plt.savefig(path2)

# endregion

# region 直方图
np.random.seed(19680801)
# example data
mu = 100  # 分布的均值
sigma = 15  # 分布的方差
x = mu + sigma * np.random.randn(437)  # 产生一组437维随机数
num_bins = 50  # 箱子的个数,也就是总共有几条条状图
fig, ax = plt.subplots()
n, bins, patches = ax.hist(x, num_bins, density=1)  # n:直方图频率向量,bins:各个bin的区间数组  patches:每个bin里面包含的数据 density将数据归一化
# 可选参数
# normed: 是否将得到的直方图向量归一化。默认为0
# facecolor: 直方图颜色   edgecolor: 直方图边框颜色  alpha: 透明度
# histtype: 直方图类型,‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’
# 最佳的拟合曲线 用虚线拟合
y = ((1 / (np.sqrt(2 * np.pi) * sigma)) *
     np.exp(-0.5 * (1 / sigma * (bins - mu))**2))
ax.plot(bins, y, '--')
ax.set_xlabel('Smarts')
ax.set_ylabel('Probability density')
ax.set_title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')

# Tweak spacing to prevent clipping of ylabel
fig.tight_layout()
plt.show()
plt.savefig(pathsave)




# endregion

# region 画路径图
# patches 补丁
import matplotlib.path as mpath
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt


fig, ax = plt.subplots()
pathsave = "F:\SOFTWARE\编程软件\python\\test.png"
Path = mpath.Path
# region 设计路径
# STOP : 1 vertex (ignored)
# A marker for the end of the entire path (currently not required and ignored)
# MOVETO : 1 vertex
# Pick up the pen and move to the given vertex.
# LINETO : 1 vertex
# Draw a line from the current position to the given vertex.
# CURVE3 : 1 control point, 1 endpoint
# Draw a quadratic Bezier curve from the current position, with the given control point, to the given end point.
# CURVE4 : 2 control points, 1 endpoint
# Draw a cubic Bezier curve from the current position, with the given control points, to the given end point.
# CLOSEPOLY : 1 vertex (ignored)
# Draw a line segment to the start point of the current polyline.
# endregion
path_data = [
    (Path.MOVETO, (1.58, -2.57)),
    (Path.CURVE4, (0.35, -1.1)),
    (Path.CURVE4, (-1.75, 2.0)),
    (Path.CURVE4, (0.375, 2.0)),
    (Path.LINETO, (0.85, 1.15)),
    (Path.CURVE4, (2.2, 3.2)),
    (Path.CURVE4, (3, 0.05)),
    (Path.CURVE4, (2.0, -0.5)),
    (Path.CLOSEPOLY, (1.58, -2.57)),
    ]
codes, verts = zip(*path_data)
path = mpath.Path(verts, codes)
# 这两句是对图像进行曲线填充 很漂亮
# patch = mpatches.PathPatch(path, facecolor='r', alpha=0.5)
# ax.add_patch(patch)

# plot control points and connecting lines
x, y = zip(*path.vertices)
line, = ax.plot(x, y, 'go-')
# 画图
ax.grid()
ax.axis('equal')
plt.savefig(pathsave)

# endregion

# region 冷暖色三维绘图
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
# 产生指定数据
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)  # 可以接受两个一维数组生成两个多维矩阵(用来绘制三维图的数据),对应两个数组中所有的(x,y)对
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
                   # Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
                       antialiased=False)  # antialiased抗锯齿 cma控制颜色也可以用color直接控制
# 设计Z轴
ax.set_zlim(-1.01, 1.01)    # z轴范围
ax.zaxis.set_major_locator(LinearLocator(10))  # 设置z轴的刻度分段数目
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))  # 设置标签显示格式 保留两位小数
fig.colorbar(surf, shrink=0.5, aspect=5)  # 边侧注释图宽 高设置
pathsave = "F:\SOFTWARE\编程软件\python\\test.png"
fig.savefig(pathsave)
# endregion

# region 柱形图表 样式比直方图多一些
# 双条形图 而且带有误差分析的
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from collections import namedtuple
n_groups = 5
means_men = (20, 35, 30, 35, 27)
std_men = (2, 3, 4, 1, 2)  # 上述数据的差值
means_women = (25, 32, 34, 20, 25)
std_women = (3, 5, 2, 3, 3)
fig, ax = plt.subplots()
index = np.arange(n_groups)  # 五组条形
bar_width = 0.35  # 条形宽度
opacity = 0.4  # 透明度
error_config = {'ecolor': '0.8'}  # ecolor 指定误差线颜色
rects1 = ax.bar(index, means_men, bar_width,  # bar_width宽度 index序列顺序 means_men基础数据 yerr误差差值 color条形图颜色
                alpha=opacity, color='b',
                yerr=std_men, error_kw=error_config,
                label='Men')

rects2 = ax.bar(index + bar_width, means_women, bar_width,
                alpha=opacity, color='r',
                yerr=std_women, error_kw=error_config,
                label='Women')

ax.set_xlabel('Group')  # 设置标题
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(index + bar_width / 2)  # 设置x轴
ax.set_xticklabels(('A', 'B', 'C', 'D', 'E'))
ax.legend()
fig.tight_layout()
pathsave = "F:\SOFTWARE\编程软件\python\\test.png"
fig.savefig(pathsave)

# 横排条形图 很多特点。。。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from collections import namedtuple
Student = namedtuple('Student', ['name', 'grade', 'gender'])  # 定义的结构体
Score = namedtuple('Score', ['score', 'percentile'])
# 初始信息
testNames = ['Pacer Test', 'Flexed Arm\n Hang', 'Mile Run', 'Agility', 'Push Ups']  # 左右轴数据
testMeta = dict(zip(testNames, ['laps', 'sec', 'min:sec', 'sec', '']))


def attach_ordinal(num):  # 帮助数字获取标准的字符显示    枚举类型 将数字变为个数表示
    suffixes = dict((str(i), v) for i, v in   # 数字与字符串的对应枚举类型
                    enumerate(['th', 'st', 'nd', 'rd', 'th',
                               'th', 'th', 'th', 'th', 'th']))
    v = str(num)
    # special case early teens
    if v in {'11', '12', '13'}:
        return v + 'th'
    return v + suffixes[v[-1]]  # 判断最后一个数来获取对应的表示形式


def format_score(scr, test):  # 右侧刻度标签字符串
    md = testMeta[test]
    if md:
        return '{0}\n{1}'.format(scr, md)
    else:
        return scr


def format_ycursor(y):  # 获取y轴名称
    y = int(y)
    if y < 0 or y >= len(testNames):
        return ''
    else:
        return testNames[y]


def plot_student_results(student, scores, cohort_size):
    #  create the figure
    fig, ax1 = plt.subplots(figsize=(9, 7))
    fig.subplots_adjust(left=0.115, right=0.88)
    fig.canvas.set_window_title('Eldorado K-8 Fitness Chart')
    pos = np.arange(len(testNames))  # 条数目
    rects = ax1.barh(pos, [scores[k].percentile for k in testNames],
                     align='center',
                     height=0.5, color='m',
                     tick_label=testNames)

    ax1.set_title(student.name)

    ax1.set_xlim([0, 100])
    ax1.xaxis.set_major_locator(MaxNLocator(10))  # x轴分刻度数目
    ax1.xaxis.grid(True, linestyle='--', which='major',
                   color='grey', alpha=.25)  # 画x的虚刻度线
    ax2 = ax1.twinx()  # 第二个坐标轴
    scoreLabels = [format_score(scores[k].score, k) for k in testNames]  # 获取标签
    ax2.set_yticks(pos)  # 确保分刻度范围同第一个y轴一样 对齐
    ax2.set_ylim(ax1.get_ylim())

    ax2.set_yticklabels(scoreLabels)  # 设置标签
    ax2.set_ylabel('Test Scores')  # 设置轴名称
    # 添加bar上的注释
    rect_labels = []
    for rect in rects:
        width = int(rect.get_width())
        rankStr = attach_ordinal(width)
        # 判断bar左右哪个宽度空间够添加文字的
        if (width < 5):
            xloc = width + 1  # 获取x位置 颜色和对齐方式
            clr = 'black'
            align = 'left'
        else:
            xloc = 0.98 * width
            clr = 'white'
            align = 'right'
        yloc = rect.get_y() + rect.get_height() / 2.0  # 获取y位置
        label = ax1.text(xloc, yloc, rankStr, horizontalalignment=align,  # 添加文字
                         verticalalignment='center', color=clr, weight='bold',
                         clip_on=True)
        rect_labels.append(label)
    ax2.fmt_ydata = format_ycursor
    fig.savefig(pathsave)


student = Student('Johnny Doe', 2, 'boy')
scores = dict(zip(testNames,
                  (Score(v, p) for v, p in
                   zip(['7', '48', '12:52', '17', '14'],
                       np.round(np.random.uniform(0, 1,
                                                  len(testNames))*100, 0)))))
cohort_size = 62  # The number of other 2nd grade boys
plot_student_results(student, scores, cohort_size)
# endregion

# region 绘制时间的图表
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import matplotlib.ticker as ticker
# 使用默认数据库的时间和数据
with cbook.get_sample_data('goog.npz') as datafile:
    r = np.load(datafile)['price_data'].view(np.recarray)
r = r[-30:]  # 30天的
date = r.date.astype('O')  # 获取日期
fig, axes = plt.subplots(ncols=2, figsize=(8, 4))
ax = axes[0]
ax.plot(date, r.adj_close, 'o-')  # r.adj_close是单个的数组数据
ax.set_title("Default")
fig.autofmt_xdate()
fig.savefig(pathsave)
# --------------------自定义部分------------------------

# endregion

# region 圆饼图
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'  # 标签
sizes = [15, 30, 45, 10]  # 数据
explode = (0, 0.1, 0, 0)  # 确定突出显示第几块
fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)  # 数字显示格式 阴影 开始角度
ax1.axis('equal')  # 确保是一个完整的圆形
fig.savefig(pathsave)
# endregion

# region 散点图
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook


with cbook.get_sample_data('goog.npz') as datafile:
    price_data = np.load(datafile)['price_data'].view(np.recarray)
price_data = price_data[-250:]  # get the most recent 250 trading days

delta1 = np.diff(price_data.adj_close) / price_data.adj_close[:-1]  # 一维数组
volume = (15 * price_data.volume[:-2] / price_data.volume[0])**2
close = 0.003 * price_data.close[:-2] / 0.003 * price_data.open[:-2]  # [a:b] 截取的意思 b为负数则倒数第几位结束的意思

fig, ax = plt.subplots()
ax.scatter(delta1[:-1], delta1[1:], c=close, s=20, alpha=0.5)  # c颜色数组
# ax.scatter(a,b,c,s,alpha) a,b为shape(n,)数组 即一维n个 c每个点颜色 s每个点面积

ax.set_xlabel(r'$\Delta_i$', fontsize=15)  # 设置坐标轴标签
ax.set_ylabel(r'$\Delta_{i+1}$', fontsize=15)
ax.set_title('Volume and percent change')
ax.grid(True)
fig.tight_layout()
fig.savefig(pathsave)
# endregion

# 打开
pathsave = "F:\SOFTWARE\编程软件\python\\test.png"
img = Image.open(pathsave)
img.show()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值