matplotlib绘图(5)

本章我们主要学习的技能有:添加阴影。

1 添加阴影效果 设置字体大小

import matplotlib.pyplot as plt
from matplotlib import patheffects
import numpy as np

fontsize=18

data=np.random.randn(70)
plt.plot(data)

title='This is figture title'
x_label='This is x axis label'
y_label='This is y axis label'

# 设置title的字体大小 竖直方向的对齐方式
title_text_obj=plt.title(title,fontsize=fontsize,verticalalignment='bottom')
# 设置路径效果  添加阴影
title_text_obj.set_path_effects([patheffects.withSimplePatchShadow()])

# 相对于对象的偏移
offset_xy=(1,-1)
rgbRed=(1.0,0.0,0.0)
alpha=0.4
# 第一个参数为偏移量 第二个参数为阴影的的颜色  第三个参数为透明度
pe=patheffects.withSimplePatchShadow(offset=offset_xy,shadow_rgbFace=rgbRed,alpha=alpha)

xlabel_obj=plt.xlabel(x_label,fontsize=fontsize,alpha=0.5)
xlabel_obj.set_path_effects([pe])

ylabel_obj=plt.ylabel(y_label,fontsize=fontsize,alpha=0.5)
ylabel_obj.set_path_effects([pe])


plt.show()

图片描述

2 图形阴影

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms

# 初始化
def setup(layout):
    assert layout is not None
    fig = plt.figure()
    ax = fig.add_subplot(layout)
    return fig, ax

# 得到绘制图标的数据
def  get_signal():
    t = np.arange(0, 2.5, 0.01)
    s = np.sin(5 * np.pi * t)
    return t, s

# 绘制线条(?line后面不加,的话返回的是list类型的数据  加上,返回的是matplotlib.lines.Line2D类型,不太清楚原因,知道的朋友可以的话请告知一下,不胜感激。)
def plot_signal(t, s):
    line ,= axes.plot(t, s, linewidth=5, color='magenta')
    return line,


def make_shadow(fig, axes, line, t, s):
    delta=2/72
    offset=transforms.ScaledTranslation(delta,-delta,fig.dpi_scale_trans)
    # 我理解的axes.transData是真实的坐标系统  不加offset的话是完全重合的
    offset_transform=axes.transData+offset

    # zoeder Z轴,把这条线放在上面会直线的底部  transform 把现在的位置装换变化到offset_transform
    axes.plot(t,s,linewidth=5,color='gray',transform=offset_transform,zorder=0.5*line.get_zorder())
    pass


if __name__ == "__main__":
    fig, axes = setup(111)
    t, s = get_signal()
    line, = plot_signal(t, s)

    make_shadow(fig,axes,line,t,s)

    plt.show()

图片描述

评论

暂无评论