Matplotlib教程代码复现(下)

  整个8月有限的学习时间都用来复习画图代码,主要就是以一篇公众号文章为基础复现。现记录复现过程,算作笔记、方便后续查找。欢迎各位关注原作者,他的整理真的很棒,详见参考学习资料。

1、参考学习资料

(1)Python、R、可视化、统计、perl原创合集

(2)Matplotlib 1.4W+字教程

(3)GitHub-scientific-visualization-book

(4)GitHub-Official Matplotlib cheat sheets

(5)Seaborn 0.9 中文文档

2、多子图绘制

# (1)  subplot
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

my_dpi = 126
fig = plt.figure(figsize=(580/my_dpi, 480/my_dpi))
margin = 0.1
fig.subplots_adjust(left=margin, right=1-margin, top=1-margin, bottom=margin)
mpl.rc('axes', linewidth=.5)

nrows, ncols = 3, 3
for i in range(nrows*ncols):
    ax = plt.subplot(ncols, nrows, i+1)
    ax.set_xticks([]), ax.set_yticks([])
plt.show()

# (2) add_gridspec
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
margin = 0.01
fig.subplots_adjust(left=margin, right=1-margin, top=1-margin, bottom=margin)
mpl.rc('axes', linewidth=.5)

gs = fig.add_gridspec(3, 3)
ax1 = fig.add_subplot(gs[0, :], xticks=[], yticks=[]) # 最上方的图片;
ax2 = fig.add_subplot(gs[1, :-1], xticks=[], yticks=[]) # 中间左边的图片;
ax3 = fig.add_subplot(gs[1:, -1], xticks=[], yticks=[]) # 中间右侧的图片;
ax4 = fig.add_subplot(gs[-1, 0], xticks=[], yticks=[]) # 左下角的图片;
ax5 = fig.add_subplot(gs[-1, -2], xticks=[], yticks=[]) # 底部中间的图片;
plt.show()

# (3) add_axes 常用
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

my_dpi=126
fig = plt.figure(figsize=(580/my_dpi, 480/my_dpi))
margin = 0.1 # 相对于fig而言
fig.subplots_adjust(left=margin, right=1-margin, top=1-margin, bottom=margin)
mpl.rc('axes', linewidth=.5)

margin = 0.125
ax1 = fig.add_axes([margin,margin,1-2*margin,1-2*margin], xticks=[], yticks=[])
ax2 = ax1.inset_axes([0.5, 0.5, 0.4, 0.4], xticks=[], yticks=[])
plt.show()

# (4) make_axes_locatable
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
margin = 0.01
fig.subplots_adjust(left=margin, right=1-margin, top=1-margin, bottom=margin)
mpl.rc('axes', linewidth=.5)

from mpl_toolkits.axes_grid1 import make_axes_locatable
margin = 0.125
ax = fig.add_axes([margin,margin,1-2*margin,1-2*margin], xticks=[], yticks=[])
divider = make_axes_locatable(ax)
cax = divider.new_horizontal(size="10%", pad=0.025)
fig.add_axes(cax)
cax.set_xticks([]), cax.set_yticks([])
plt.show()

 

学习笔记

2.1 官网示例

(1) matplotlib.pyplot.subplots官方文档
  matplotlib.pyplot.subplots官方文档

(2) matplotlib.axes.Axes.inset_axes官方文档
  matplotlib.axes.Axes.inset_axes官方文档

(3) Arranging multiple Axes in a Figure官方文档
   Arranging multiple Axes in a Figure官方文档

(4) 中文代码讲解示例
  中文代码讲解示例

2.2 学习笔记

1、matplotlib.pyplot api方式添加子图

plt.subplot(221)
    plt.subplots_adjust(left=0.125, bottom=-0.51, right=1.3, top=0.88, wspace=0.2, hspace=0.2)

        subplots_adjust函数:  
 			https://blog.csdn.net/lty_sky/article/details/104589415/ left, right, bottom, top:子图所在区域的边界。要保证left < right, bottom < top,否则会报错。  
		 A,B可以理解是图像左下角点的坐标,C,D可以理解为图像右上角点的坐标,至于E,F则是控制子图之间的距离。注意这些值都是0到1之间的值,代表百分比。

2、面向对象方式添加子图

fig, axs = plt.subplots(2,2,figsize=(480/my_dpi,480/my_dpi),dpi=my_dpi,    
          sharex=False,#x轴刻度值共享开启 
          sharey=False,#y轴刻度值共享关闭  
 )

     #fig为matplotlib.figure.Figure对象, axs为matplotlib.axes.Axes,把fig分成2x2的子图
       #axs[0][0]、axs[0][1]、axs[1][0]、axs[1][1], 各个子图,https://blog.csdn.net/qq_39622065/article/details/82909421

3、matplotlib.pyplot add_subplot方式添加子图

	 fig = plt.figure(figsize=(480/my_dpi,480/my_dpi),dpi=my_dpi) # 对象  
	 fig.add_subplot(221) # 2*2的4子图中, 在指定位置1添加子图  
	 
	 plt.plot([1,2,3]) plt.title('fig.add_subplot(222)') # 子图的title  
	 plt.suptitle('matplotlib.pyplot api:add_subplot',color='r') # 整个画布的title

4、matplotlib.gridspec.GridSpec方式添加子图
  略, 使用时再看

5、子图中绘制子图
  略, 使用时再看, GridSpec、GridSpecFromSubplotSpec的功能结合

6、任意位置绘制子图

	plt.axes([0.7, 0.2, 0.15, 0.15], ## [left, bottom, width, height]四个参数(fractions of figure)可以非常灵活的调节子图中子图的位置)  
	plt.bar([1,2,3],[1,2,3],color=['r','b','g'])

刻度属性设置:  
	 plt.tick_params(axis='x', labelsize=20, rotation=45)#x轴标签旋转、字号等

3、文本text设置

import numpy as np
import matplotlib.pyplot as plt

dpi = 100
fig = plt.figure(dpi=100)
ax = fig.add_axes([0,0,1,1], frameon=False,
                  xlim=(0,4.25), ylim=(0,1.5), xticks=[], yticks=[])

fontsize = 48
renderer = fig.canvas.get_renderer()
horizontalalignment = "left"
verticalalignment = "center"
position = (0.25, 1.5/2)
color = "0.25"

# Compute vertical and horizontal alignment offsets
text = ax.text(0, 0, "Matplotlib", fontsize=fontsize)
yoffset = {}
for alignment in ["top", "center", "baseline", "bottom"]:
    text.set_verticalalignment(alignment)
    y = text.get_window_extent(renderer).y0/dpi
    yoffset[alignment] = y

xoffset = {}
for alignment in ["left", "center", "right"]:
    text.set_horizontalalignment(alignment)
    x = text.get_window_extent(renderer).x0/dpi
    xoffset[alignment] = x

# Actual positioning of the text
text.set_horizontalalignment(horizontalalignment)
text.set_verticalalignment(verticalalignment)
text.set_position(position)


for name,y in yoffset.items():
    y = position[1] - y + yoffset[verticalalignment]
    plt.plot([0.1, 3.75], [y, y], linewidth=0.5, color=color)
    plt.text(3.75, y, " "+name, color=color,
             ha="left", va="center", size="x-small")

for name,x in xoffset.items():
    x = position[0] - x + xoffset[horizontalalignment]
    plt.plot([x,x], [0.25, 1.25], linewidth=0.5, color=color)
    plt.text(x, 0.24, name, color = color,
             ha="center", va="top", size="x-small")

P = []
for x in xoffset.values():
    x = position[0] - x + xoffset[horizontalalignment]
    for y in yoffset.values():
        y = position[1] - y + yoffset[verticalalignment]
        P.append((x,y))
P = np.array(P)

ax.scatter(P[:,0], P[:,1], s=10, zorder=10,
           facecolor="white", edgecolor=color, linewidth=0.75)

epsilon = 0.05
plt.text(P[3,0]+epsilon, P[3,1]-epsilon, "(0,0)",
         color=color, ha="left", va="top", size="xx-large")
plt.text(P[8,0]-epsilon, P[8,1]+epsilon, "(1,1)",
         color=color, ha="right", va="bottom", size="xx-large")

plt.show()

 

学习笔记

3.1 官网示例

(1) 官方文档
    https://matplotlib.org/stable/tutorials/text/text_props.html

(2) 参考示例
    Python可视化31|matplotlib-图添加文本(text)及注释(annotate)

3.2 学习笔记

1、添加文本(matplotlib.pyplot.text)
(1) 文本基本参数设置

plt.text(x=2.2,#文本x轴坐标  
	y=8, #文本y轴坐标  
	s='basic unility of text', #文本内容  
	rotation=1,#文字旋转  
	ha='left',#x=2.2是文字的左端位置,可选'center', 'right', 'left'  
	va='baseline',#y=8是文字的低端位置,可选'center', 'top', 'bottom', 'baseline', 'center_baseline'  
	fontdict=dict(fontsize=12, color='r', family='monospace',#字体,可选'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'  
	weight='bold',#磅值,可选'light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black')#字体属性设置  
)

(2) 给文本加上背景框

plt.text(  
		#添加文字背景色  
		bbox={'facecolor': '#74C476', #填充色  
			   'edgecolor':'b',#外框色  
			   'alpha': 0.5, #框透明度  
			   'pad': 8,#本文与框周围距离  
				} 
)text.set_color('b') #修改文字颜色

(3)背景文本框形状

   'boxstyle':'sawtooth'    

    fig.canvas.get_renderer()  
   		 https://www.modb.pro/db/412419  
    	 调用bbox = fig.get_tightbbox(fig.canvas.get_renderer()),结果是包围图中每个Artist的边界框,已经转换为单位英寸

 

4、注释设置

# 注释(annotate)
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(6,1))
ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect=1)

plt.scatter([5.5], [0.75], s=100, c="k")
plt.xlim(0, 6), plt.ylim(0, 1)
plt.xticks([]), plt.yticks([])

plt.annotate("Annotation", (5.5, .75), (0.1, .75), size=16, va="center",
             arrowprops=dict(facecolor='black', shrink=0.05))

plt.text( 5.5, 0.6, "xy\nycoords", size=10, va="top", ha="center", color=".5")
plt.text( .75, 0.6, "xytext\ntextcoords", size=10, va="top", ha="center", color=".5")
plt.show()

# 注释箭头类型
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

styles = mpatches.ArrowStyle.get_styles()
def demo_con_style(ax, connectionstyle):
    ax.text(.05, .95, connectionstyle.replace(",", ",\n"),
            family="Source Code Pro",
            transform=ax.transAxes, ha="left", va="top", size="x-small")

fig, ax = plt.subplots(dpi=100, frameon=False) # frameon=False, 则图示会被直接绘制在图片上
ax.axis("off")
for i,style in enumerate(mpatches.ArrowStyle.get_styles()):
    # print(i, style) # 16种线条风格
    x0, y0 = 5 + 5*(i%3), -(i//3)
    x1, y1 = 1 + 5*(i%3), -(i//3)
    ax.plot([x0, x1], [y0, y1], ".", color="0.25") # 画布上定位24组位点
    ax.annotate("",
                xy=(x0, y0), xycoords='data',
                xytext=(x1, y1), textcoords='data',
                arrowprops=dict(arrowstyle=style,
                                color="black",
                                shrinkA=5, shrinkB=5,
                                patchA=None, patchB=None,
                                connectionstyle="arc3,rad=0"))
    ax.text( (x1+x0)/2, y0-0.2, style,
             family = "Source Code Pro", ha="center", va="top")
plt.show()

# 注释箭头线型
import matplotlib.pyplot as plt

# 依据调整connectionstyle, 画不同的子图
def demo_con_style(ax, connectionstyle):
    x1, y1 = 0.3, 0.2
    x2, y2 = 0.8, 0.6
    ax.plot([x1, x2], [y1, y2], ".")
    ax.annotate("",
                xy=(x1, y1), xycoords='data',
                xytext=(x2, y2), textcoords='data',
                arrowprops=dict(arrowstyle="->", color="0.5",
                                shrinkA=5, shrinkB=5,
                                patchA=None, patchB=None,
                                connectionstyle=connectionstyle),
                )
    ax.text(.05, .95, connectionstyle.replace(",", ",\n"),
            family="Source Code Pro",
            transform=ax.transAxes, ha="left", va="top", size="x-small")

fig, axs = plt.subplots(3, 3, dpi=100)
demo_con_style(axs[0, 0], "arc3,rad=0")
demo_con_style(axs[0, 1], "arc3,rad=0.3")
demo_con_style(axs[0, 2], "angle3,angleA=0,angleB=90")
demo_con_style(axs[1, 0], "angle,angleA=-90,angleB=180,rad=0")
demo_con_style(axs[1, 1], "angle,angleA=-90,angleB=180,rad=25")
demo_con_style(axs[1, 2], "arc,angleA=-90,angleB=0,armA=0,armB=40,rad=0")
demo_con_style(axs[2, 0], "bar,fraction=0.3")
demo_con_style(axs[2, 1], "bar,fraction=-0.3")
demo_con_style(axs[2, 2], "bar,angle=180,fraction=-0.2")

# axs.flat 去掉每个子图的坐标轴信息
for ax in axs.flat:
    ax.set(xlim=(0, 1), ylim=(0, 1), xticks=[], yticks=[], aspect=1) # 即x和y的缩放比例相同
fig.tight_layout(pad=0.2)   # 调整9个子图之间的空白距离
plt.show()

学习笔记

4.1 官网示例

  (1) https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.annotate.html

  (2) # Python可视化31|matplotlib-图添加文本(text)及注释(annotate)

  (3) # Matplotlib 可视化之箭头与标注的高级应用

4.2 学习笔记

1、添加注释(matplotlib.pyplot.annotate)
(1) 基本参数设置

plt.annotate('basic unility of annotate',
             xy=(2, 8),#箭头末端位置

             xytext=(1.0, 8.75),#文本起始位置

             #箭头属性设置
            arrowprops=dict(facecolor='#74C476',
                            shrink=1,#箭头的收缩比
                            alpha=0.6,
                            width=7,#箭身宽
                            headwidth=40,#箭头宽
                            hatch='--',#填充形状
                            frac=0.8,#身与头比
                            #其它参考matplotlib.patches.Polygon中任何参数
                           ),
            )

(2) 修改箭头形状
  arrowstyle=‘-|>’,#箭头类型修改

(3) 箭头弯曲
  arrowstyle=‘-|>’, connectionstyle=‘arc3,rad=0.5’,#有多个参数可选

(4) 跨子图注释
  styles = mpatches.ArrowStyle.get_styles()
  通过mpatches.ArrowStyle.get_styles()方法查看所有可以设置的样式

2、fig.tight_layout()函数
  功能:使得子图横纵坐标更加紧凑,主要用于自动调整图区的大小以及间距,使所有的绘图及其标题、坐标轴标签等都可以不重叠的完整显示在画布上。

参数:
  Pad:用于设置绘图区边缘与画布边缘的距离大小
  w_pad:用于设置绘图区之间的水平距离的大小
  H_pad:用于设置绘图区之间的垂直距离的大小

 

5、坐标轴刻度Tick设置

# 刻度间距设置
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

# Setup a plot such that only the bottom spine is shown
def setup(ax):
    ax.spines['right'].set_color('none')    # 图片右轴的颜色
    ax.spines['left'].set_color('none')
    ax.yaxis.set_major_locator(ticker.NullLocator())    # X轴刻度线步长;
    ax.spines['top'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')
    ax.tick_params(which='major', width=1.00)   # 对坐标轴刻度(tick)与刻度值(tick label)操作
    ax.tick_params(which='major', length=5)
    ax.tick_params(which='minor', width=0.75)
    ax.tick_params(which='minor', length=2.5)
    ax.set_xlim(0, 5)
    ax.set_ylim(0, 1)
    ax.patch.set_alpha(0.0)


fig = plt.figure(figsize=(8, 5))
fig.patch.set_alpha(0.0)
n = 8

fontsize = 18
family = "Source Code Pro"

# Null Locator
ax = plt.subplot(n, 1, 1)
setup(ax)
ax.xaxis.set_major_locator(ticker.NullLocator())
ax.xaxis.set_minor_locator(ticker.NullLocator())
ax.text(0.0, 0.1, "ticker.NullLocator()",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# Multiple Locator
ax = plt.subplot(n, 1, 2)
setup(ax)
ax.xaxis.set_major_locator(ticker.MultipleLocator(0.5))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1))
ax.text(0.0, 0.1, "ticker.MultipleLocator(0.5)",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# Fixed Locator
ax = plt.subplot(n, 1, 3)
setup(ax)
majors = [0, 1, 5]
ax.xaxis.set_major_locator(ticker.FixedLocator(majors))
minors = np.linspace(0, 1, 11)[1:-1]
ax.xaxis.set_minor_locator(ticker.FixedLocator(minors))
ax.text(0.0, 0.1, "ticker.FixedLocator([0, 1, 5])",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# Linear Locator
ax = plt.subplot(n, 1, 4)
setup(ax)
ax.xaxis.set_major_locator(ticker.LinearLocator(3))
ax.xaxis.set_minor_locator(ticker.LinearLocator(31))
ax.text(0.0, 0.1, "ticker.LinearLocator(numticks=3)",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# Index Locator
ax = plt.subplot(n, 1, 5)
setup(ax)
ax.plot(range(0, 5), [0]*5, color='white')
ax.xaxis.set_major_locator(ticker.IndexLocator(base=.5, offset=.25))
ax.text(0.0, 0.1, "ticker.IndexLocator(base=0.5, offset=0.25)",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# Auto Locator
ax = plt.subplot(n, 1, 6)
setup(ax)
ax.xaxis.set_major_locator(ticker.AutoLocator())
ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())
ax.text(0.0, 0.1, "ticker.AutoLocator()",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# MaxN Locator
ax = plt.subplot(n, 1, 7)
setup(ax)
ax.xaxis.set_major_locator(ticker.MaxNLocator(4))
ax.xaxis.set_minor_locator(ticker.MaxNLocator(40))
ax.text(0.0, 0.1, "ticker.MaxNLocator(n=4)",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# Log Locator
ax = plt.subplot(n, 1, 8)
setup(ax)
ax.set_xlim(10**3, 10**10)
ax.set_xscale('log')
ax.xaxis.set_major_locator(ticker.LogLocator(base=10.0, numticks=15))
ax.text(0.0, 0.1, "ticker.LogLocator(base=10, numticks=15)",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# Push the top of the top axes outside the figure because we only show the
# bottom spine.
plt.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=1.05)

# 刻度标签格式化输出
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

# Setup a plot such that only the bottom spine is shown
def setup(ax):
    ax.spines['right'].set_color('none')
    ax.spines['left'].set_color('none')
    ax.yaxis.set_major_locator(ticker.NullLocator())
    ax.spines['top'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')
    ax.tick_params(which='major', width=1.00, length=5)
    ax.tick_params(which='minor', width=0.75, length=2.5, labelsize=10)
    ax.set_xlim(0, 5)
    ax.set_ylim(0, 1)
    ax.patch.set_alpha(0.0)


fig = plt.figure(figsize=(8, 5))
fig.patch.set_alpha(0.0)
n = 7

fontsize = 18
family = "Source Code Pro"

# Null formatter
ax = fig.add_subplot(n, 1, 1)
setup(ax)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
ax.xaxis.set_major_formatter(ticker.NullFormatter())
ax.xaxis.set_minor_formatter(ticker.NullFormatter())
ax.text(0.0, 0.1, "ticker.NullFormatter()", family=family,
        fontsize=fontsize, transform=ax.transAxes)

# Fixed formatter
ax = fig.add_subplot(n, 1, 2)
setup(ax)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.0))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
majors = ["", "0", "1", "2", "3", "4", "5"]
ax.xaxis.set_major_formatter(ticker.FixedFormatter(majors))
minors = [""] + ["%.2f" % (x-int(x)) if (x-int(x))
                 else "" for x in np.arange(0, 5, 0.25)]
ax.xaxis.set_minor_formatter(ticker.FixedFormatter(minors))
ax.text(0.0, 0.1, "ticker.FixedFormatter(['', '0', '1', ...])",
        family=family, fontsize=fontsize, transform=ax.transAxes)


# FuncFormatter can be used as a decorator
@ticker.FuncFormatter
def major_formatter(x, pos):
    return "[%.2f]" % x


ax = fig.add_subplot(n, 1, 3)
setup(ax)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
ax.xaxis.set_major_formatter(major_formatter)
ax.text(0.0, 0.1, 'ticker.FuncFormatter(lambda x, pos: "[%.2f]" % x)',
        family=family, fontsize=fontsize, transform=ax.transAxes)


# FormatStr formatter
ax = fig.add_subplot(n, 1, 4)
setup(ax)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter(">%d<"))
ax.text(0.0, 0.1, "ticker.FormatStrFormatter('>%d<')",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# Scalar formatter
ax = fig.add_subplot(n, 1, 5)
setup(ax)
ax.xaxis.set_major_locator(ticker.AutoLocator())
ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())
ax.xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))
ax.text(0.0, 0.1, "ticker.ScalarFormatter()",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# StrMethod formatter
ax = fig.add_subplot(n, 1, 6)
setup(ax)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
ax.xaxis.set_major_formatter(ticker.StrMethodFormatter("{x}"))
ax.text(0.0, 0.1, "ticker.StrMethodFormatter('{x}')",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# Percent formatter
ax = fig.add_subplot(n, 1, 7)
setup(ax)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
ax.xaxis.set_major_formatter(ticker.PercentFormatter(xmax=5))
ax.text(0.0, 0.1, "ticker.PercentFormatter(xmax=5)",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# Push the top of the top axes outside the figure because we only show the
# bottom spine.
fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=1.05)

学习笔记

5.1 官网示例

  https://matplotlib.org/stable/api/ticker_api.html
  python可视化|matplotlib02-matplotlib.pyplot坐标轴|刻度值|刻度|标题设置

5.2 学习笔记

  下面代码分为两个部分:刻度标签格式化输出、刻度间距设置
  可以整体跑完代码,再一段段代码逐渐添加,通过变化,理解代码含义; 刻度间距设置,

  展示了8种刻度线划分间距的方式;
  刻度标签格式化输出, 展示了7种刻度标签格式化;

 

六、图例(legend)设置

#图例(legend)|位置
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(4,4))
ax = fig.add_axes([0.15, 0.15, .7, .7], frameon=True, aspect=1,
                  xticks=[], yticks=[])   # frameon=False, 则图例会被直接绘制在图片上; aspect=1, 即x和y的缩放比例相同

def text(x, y, _text):
    color= "C1"
    if not 0 < x < 1 or not 0 < y < 1:  color = "C0"
    size = 0.15
    ax.text(x, y, _text, color="white", #bbox={"color": "C1"},
            size="xx-large", weight="bold", ha="center", va="center")
    rect = plt.Rectangle((x-size/2, y-size/2), size, size, facecolor=color,
                         zorder=-10, clip_on=False) # 矩形设置参数
    ax.add_patch(rect)  # 将补丁添加到轴的补丁

def point(x, y):
    ax.scatter([x], [y], facecolor="C0", edgecolor="white",
               zorder=10, clip_on=False)

d = .1
e = .15/2

text(  d,   d, "1"), text( 0.5,   d, "2"), text(1-d,   d, "3")
text(  d, 0.5, "4"), text( 0.5, 0.5, "5"), text(1-d, 0.5, "6")
text(  d, 1-d, "7"), text( 0.5, 1-d, "8"), text(1-d, 1-d, "9")

text( -d, 1-d, "A"), text( -d, 0.5, "B"), text(  -d,   d, "C")
point(-d+e, 1-d+e), point(-d+e, 0.5), point(-d+e, d-e),

text(  d,  -d, "D"), text(0.5,  -d, "E"), text( 1-d,  -d, "F")
point(d-e, -d+e), point(0.5, -d+e), point(1-d+e, -d+e),

text(1+d,   d, "G"), text(1+d, 0.5, "H"), text( 1+d, 1-d, "I")
point(1+d-e, d-e), point(1+d-e, .5), point(1+d-e, 1-d+e),

text(1-d, 1+d, "J"), text(0.5, 1+d, "K"), text(   d, 1+d, "L")
point(1-d+e, 1+d-e), point(0.5, 1+d-e), point(d-e, 1+d-e),

plt.xlim(0,1), plt.ylim(0,1)
plt.show()

学习笔记

6.1 官网示例

  https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html

  Python可视化32|matplotlib-断裂坐标轴(broken_axis)|图例(legend)详解

6.2 学习笔记

  可以整体跑完代码,再一段段代码逐渐添加,通过变化,理解代码含义;
生成三组橘色矩阵; 生成三组蓝色矩阵、并定位散点; XY轴缩减距离、调整边框位置;

  最终代码会形成如下9个内部位置、12个外部位置, 方便处理定位;

	1: lower left	 2: lower center 	3: lower right  
	4: left 	5: center 	6: right  
	7: upper left 	8: upper center 	9: upper right
	
	A: upper right / (‐.1,.9) 	B: right / (‐.1,.5)  
	C: lower right / (‐.1,.1) 	D: upper left / (‐.1,‐.1)
	
	E: upper center / (.5,‐.1)	 F: upper right / (.9,‐.1)  
	G: lower left / (1.1,.1) 	H: left / (1.1,.5)
	
	I: upper left / (1.1,.9) 	J: lower right / (.9,1.1)  
	K: lower center / (.5,1.1) 	L: lower left / (.1,1.1)

 

7、Colors和Color maps

# 一、内置单颜色 源自官网实例
import matplotlib.pyplot as plt
import numpy as np

t = np.linspace(0.0, 2.0, 201)
s = np.sin(2 * np.pi * t)

# 1) RGB tuple:
fig, ax = plt.subplots(facecolor=(.18, .31, .31),figsize=(10,5)) #整体背景, RGB 或者 RGBA 元组格式颜色
# 2) hex string:
ax.set_facecolor('#986DB2') # ax图片背景, RGB or RGBA对应的hex 格式颜色
# 3) gray level string:
ax.set_title('Voltage vs. time chart', color='0.7')  # [0,1]之间的任意浮点数
# 4) single letter color string
ax.set_xlabel('time (s)', color='c')  # BASE_COLORS设置
# 5) a named color:
ax.set_ylabel('voltage (mV)', color='peachpuff')  # CSS4_COLORS设置
# 6) a named xkcd color:
ax.plot(t, s, 'xkcd:crimson')  # XKCD_COLORS色号
# 7) Cn notation:
ax.plot(t, .7*s, color='C4', linestyle='--')  # 'Cn'格式
# 8) tab notation:
ax.tick_params(labelcolor='tab:orange')  # TABLEAU_COLORS

ax.set_facecolor('#64363C')
plt.show()

# 二、自带颜色条Colormap
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
plt.figure(dpi=150)

##ListedColormap
#取多种颜色, 以下3种方法均可以提取同样的颜色
plt.subplot(1,4,1)
# plt.bar(range(5),range(1,6),color=plt.cm.Accent(range(5)))
# plt.bar(range(5),range(1,6),color=plt.cm.get_cmap('Accent')(range(5)))
plt.bar(range(5),range(1,6),color=plt.get_cmap('Accent')(range(5)))

#取某一种颜色
plt.subplot(1,4,2)
plt.bar(range(5),range(1,6),color=plt.cm.Accent(4))

##LinearSegmentedColormap
#取多种颜色, 取一组颜色中的特定几个;
plt.subplot(1,4,3)
plt.bar(range(5),range(1,6),color=plt.get_cmap('Blues')(np.linspace(0, 1, 5)))

#取一种颜色
plt.subplot(1,4,4)
plt.bar(range(5),range(1,6),color=plt.get_cmap('Blues')(3))
plt.show()


# 三、seaborn调色盘
# (1)颜色盘颜色展示
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(dpi=250)
sns.palplot(sns.color_palette())    #输出默认颜色
    # sns.palplot(sns.color_palette(palette='Accent')) #使用matplotlib中的colormap
    # sns.palplot(sns.color_palette(n_colors=21))    #返回颜色种类,超过了自动循环
    # sns.palplot(sns.color_palette(n_colors=21, desat=0.2) #设置颜色饱和度
print(sns.color_palette())
plt.show()


# (2)循环使用色盘
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
plt.figure(dpi=100)
with sns.color_palette(n_colors=21):
   _ = plt.plot(np.c_[np.zeros(21), np.arange(21)].T)
plt.show()


# (3)传入hex 格式颜色号给sns.color_palette
import seaborn as sns
import matplotlib.pyplot as plt
flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]
sns.palplot(sns.color_palette(flatui))
plt.show()

#(4)颜色使用
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(dpi=100)

plt.subplot(1,2,1)
plt.bar([1,2,3],[1,2,3], color=sns.color_palette()[0])#取一种颜色

plt.subplot(1,2,2)
plt.bar([1,2,3],[1,2,3], color=sns.color_palette()[0:3])#取三种颜色
plt.show()

#(5) diverging_palette()
import seaborn as sns
import matplotlib.pyplot as plt
sns.palplot(sns.color_palette("coolwarm", 7))
sns.palplot(sns.diverging_palette(240, 10, n=9)) # n=1000时,热图效果为渐变色,更方便看;
sns.palplot(sns.diverging_palette(150, 275, s=80, l=55, n=9))
sns.palplot(sns.diverging_palette(250, 15, s=75, l=40,
                                  n=9, center="dark"))
plt.show()

学习笔记

  可以直接使用颜色代码来精准定义, 或者通过get_cmap()函数来获取某组颜色;
  uniform、sequential、diverging是get_cmap()函数三个非常重要的功能;

以下资料可供查询、使用:
(1) 内置单颜色
  Python可视化|matplotlib05-内置单颜色(一)

(2) 外部单颜色
  Python可视化|matplotlib06-外部单颜色(二)

(3) 自带颜色条Colormap
  Python可视化|matplotlib07-自带颜色条Colormap(三)

(5) 提取图片颜色绘图
  Python|R可视化|09-提取图片颜色绘图(五-颜色使用完结篇)

(6) 绘图颜色色号速查1
  颜色小抄免费大放送(一)

(7) 绘图颜色色号速查2
  颜色小抄免费大放送(二)

(8) seaborn调色盘
  Python可视化18|seborn-seaborn调色盘(六)
   ‘sequential’(渐变色), ‘diverging’(不可描述,自己跑下最后的示例代码), ‘qualitative’(各种颜色区分鲜明)

 

8、line和marker设置

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']  # 用于显示中文
plt.rcParams['axes.unicode_minus'] = False  # 用于显示中文
plt.figure(dpi=200)
#常规marker使用
plt.plot([1,2,3],[1,2,3],marker=4, markersize=15, color='lightblue',label='常规marker')
plt.plot([1.8,2.8,3.8],[1,2,3],marker='2', markersize=15, color='#ec2d7a',label='常规marker')

#非常规marker使用
#注意使用两个$符号包围名称
plt.plot([1,2,3],[4,5,6],marker='$\circledR$', markersize=15, color='r', alpha=0.5,label='非常规marker')
plt.plot([1.5,2.5,3.5],[1.25,2.1,6.5],marker='$\heartsuit$', markersize=15, color='#f19790', alpha=0.5,label='非常规marker')
plt.plot([1,2,3],[2.5,6.2,8],marker='$\clubsuit$', markersize=15, color='g', alpha=0.5,label='非常规marker')

#自定义marker
plt.plot([1.2,2.2,3.2],[1,2,3],marker='$666$', markersize=15, color='#2d0c13',label='自定义marker')
plt.legend(loc='upper left')
for i in ['top','right']:
    plt.gca().spines[i].set_visible(False)

plt.show()

学习笔记

8.1 官网示例

  https://matplotlib.org/stable/tutorials/text/mathtext.html
  Python可视化|matplotlib03-一文掌握marker和linestyle使用
 

9、子图与figure之间位置

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection


fig = plt.figure(dpi=120)
ax = fig.add_axes([0,0,1,1], frameon=False, aspect=1,
                  xlim=(0-5,100+10), ylim=(-10,80+5), xticks=[], yticks=[])


box = mpatches.FancyBboxPatch(
    (0,0), 100, 83,  mpatches.BoxStyle("Round", pad=0, rounding_size=2),
    linewidth=1., facecolor="0.9", edgecolor="black")
ax.add_artist(box)

box = mpatches.FancyBboxPatch(
    (0,0), 100, 75, mpatches.BoxStyle("Round", pad=0, rounding_size=0),
    linewidth=1., facecolor="white", edgecolor="black")
ax.add_artist(box)


box = mpatches.Rectangle(
    (5,5), 45, 30, zorder=10,
    linewidth=1.0, facecolor="white", edgecolor="black")
ax.add_artist(box)

box = mpatches.Rectangle(
    (5,40), 45, 30, zorder=10,
    linewidth=1.0, facecolor="white", edgecolor="black")
ax.add_artist(box)

box = mpatches.Rectangle(
    (55,5), 40, 65, zorder=10,
    linewidth=1.0, facecolor="white", edgecolor="black")
ax.add_artist(box)

# Window button
X, Y = [5,10,15], [79,79,79]
plt.scatter(X, Y, s=75,  zorder=10,
            edgecolor="black", facecolor="white", linewidth=1)


# Window size extension
X, Y = [0, 0], [0, -8]
plt.plot(X, Y, color="black", linestyle=":", linewidth=1, clip_on=False)

X, Y = [100, 100], [0, -8]
plt.plot(X, Y, color="black", linestyle=":", linewidth=1, clip_on=False)

X, Y = [100, 108], [0, 0]
plt.plot(X, Y, color="black", linestyle=":", linewidth=1, clip_on=False)

X, Y = [100, 108], [75, 75]
plt.plot(X, Y, color="black", linestyle=":", linewidth=1, clip_on=False)


def ext_arrow(p0,p1,p2,p3):
    p0, p1 = np.asarray(p0), np.asarray(p1)
    p2, p3 = np.asarray(p2), np.asarray(p3)
    ax.arrow(*p0, *(p1-p0), zorder=20, linewidth=0,
             length_includes_head=True, width=.4,
             head_width=2, head_length=2, color="black")
    ax.arrow(*p3, *(p2-p3), zorder=20, linewidth=0,
             length_includes_head=True, width=.4,
             head_width=2, head_length=2, color="black")
    plt.plot([p1[0],p2[0]], [p1[1],p2[1]], linewidth=.9, color="black")

def int_arrow(p0,p1):
    p0, p1 = np.asarray(p0), np.asarray(p1)
    ax.arrow(*((p0+p1)/2), *((p1-p0)/2), zorder=20, linewidth=0,
             length_includes_head=True, width=.4,
             head_width=2, head_length=2, color="black")
    ax.arrow(*((p0+p1)/2), *(-(p1-p0)/2), zorder=20, linewidth=0,
             length_includes_head=True, width=.4,
             head_width=2, head_length=2, color="black")

x = 0
y = 10
ext_arrow( (x-4,y), (x,y), (x+5,y), (x+9,y) )
ax.text(x+9.5, y, "left", ha="left", va="center", size="x-small", zorder=20)

x += 50
ext_arrow( (x-4,y), (x,y), (x+5,y), (x+9,y) )
ax.text(x-4.5, y, "wspace", ha="right", va="center", size="x-small", zorder=20)

x += 45
ext_arrow( (x-4,y), (x,y), (x+5,y), (x+9,y) )
ax.text(x-4.5, y, "right", ha="right", va="center", size="x-small", zorder=20)

y = 0
x = 25
ext_arrow( (x,y-4), (x,y), (x,y+5), (x,y+9) )
ax.text(x, y+9.5, "bottom", ha="center", va="bottom", size="x-small", zorder=20)

y += 35
ext_arrow( (x,y-4), (x,y), (x,y+5), (x,y+9) )
ax.text(x, y-4.5, "hspace", ha="center", va="top", size="x-small", zorder=20)

y += 35
ext_arrow( (x,y-4), (x,y), (x,y+5), (x,y+9) )
ax.text(x, y-4.5, "top", ha="center", va="top", size="x-small", zorder=20)

int_arrow((0,-5), (100,-5))
ax.text(50, -5, "figure width", backgroundcolor="white", zorder=30,
        ha="center", va="center", size="x-small")

int_arrow((105,0), (105,75))
ax.text(105, 75/2, "figure height", backgroundcolor="white", zorder=30,
        rotation = "vertical", ha="center", va="center", size="x-small")

int_arrow((55,62.5), (95,62.5))
ax.text(75, 62.5, "axes width", backgroundcolor="white", zorder=30,
        ha="center", va="center", size="x-small")

int_arrow((62.5,5), (62.5,70))
ax.text(62.5, 35, "axes height", backgroundcolor="white", zorder=30,
        rotation = "vertical", ha="center", va="center", size="x-small")
plt.show()

学习笔记

8.1 官网示例

  https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots_adjust.html
  代码看的不是太明白,用到的时候再细看吧。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值