Matplotlib绘图-颜色,字体,刻度,label,tick_label,粗细,图例设置

Python 中的图形绘制(二) 4、条形图 下面介绍条形图的画法。 4.1 代码 importmatplotlib.pyplot as plt # 柱线左侧的 x 坐标 左=[ 1,2,3,4,5] # 柱线高度 高度=[ 10,24,36,40,5] # 条形图的标签 tick_label=['一','二','三','四','五'] # 绘制条形图 plt.bar(左,高度,tick_label=tick_label, 宽度=0.8,颜色=["红色","绿色"... 阅读详情

From: subce

Tips

整理一下关于绘图的基本设置,主要包括:

  • 自定义legend
  • 二维图tick的长度和粗细
  • 孪生x轴、y轴
  • 设置二维图边框粗细
  • 给三维图添加边框
  • 设置三维图背景颜色为白色
  • 三维图tick的长度和粗细

Legend

# 自定义legend
lenline1 = mlines.Line2D([], [], color='r', marker='s', linewidth=0.85,
                          markersize=5, label='Learning rate=0.0001')
lenline2 = mlines.Line2D([], [], color='g', marker='D', linewidth=0.85,
                          markersize=5, label='Learning rate=0.00001')
lenline3 = mlines.Line2D([], [], color='b', marker='^', linewidth=0.85,
                          markersize=5, label='Learning rate=0.001')

legend = ax.legend(handles=[lenline1,lenline2,lenline3], loc='lower right', bbox_to_anchor=(0.99, 0.01),ncol=1,frameon=True,fancybox=False,
                 facecolor='white',edgecolor='red')  # Add a legend.

Legend guide

2D

import numpy as np

import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D

import matplotlib.font_manager as fm
from matplotlib.ticker import MultipleLocator,AutoMinorLocator


# 1pt = 0.35146mm = 0.035146cm
# 1inch = 2.54cm = 72.27pt
# 图表坐标轴线条粗细最佳为 0.2mm = [0.57pt]
# 线条粗细在0.1mm-0.4mm之间 >>> 0.3mm = [0.85pt]
# 原则上不超过14号字,尽量使用7-12号字,尽量少使用小于6号以下的字体
# 最多见的文字大小推荐使用7、8、9号字 >> [9pt]

# 图片大小 单位厘米
fw = 10/2.54
fh = 8/2.54

# 设置全局的字体
mpl.rcParams['font.family'] = 'serif'
mpl.rcParams['font.serif'] = 'Times New Roman'
mpl.rcParams['font.style'] = 'normal'
mpl.rcParams['font.variant'] = 'normal'
mpl.rcParams['font.weight'] = 'normal'
mpl.rcParams['font.stretch'] ='normal'
mpl.rcParams['font.size'] = 9

# 第一种方式设置字体
font0 = {'fontfamily': 'serif',
         'fontname': 'Times New Roman',
         'fontstyle': 'normal',
         'fontvariant': 'normal',
         'fontweight': 'normal',
         'fontstretch': 'normal',
         'fontsize': 9}

# 第二种方式设置字体
tick_font = fm.FontProperties(family='Times New Roman', style='normal', variant='normal', weight='normal',
                           stretch='normal', size=9)
x = np.linspace(0, 2, 100)

# 1pt = 0.35146mm = 0.035146cm
# 1inch = 2.54cm = 72.27pt

#plt.rcParams['xtick.direction'] = 'in'
#plt.rcParams['ytick.direction'] = 'in'
fig = plt.figure(figsize=(fw,fh))
# figsize=(8/2.54,6/2.54),dpi=72
ax = fig.add_subplot(111)  # Create a figure and an axes.

ax.plot(x, x, label='linear',linewidth=0.85)  # Plot some data on the axes.
ax.plot(x, x**2, label='quadratic',linewidth=0.85)  # Plot more data on the axes...
ax.plot(x, x**3, label='cubic',linewidth=0.85)  # ... and some more.

# 图形四周是否显示tick
ax.tick_params(bottom=True, top=True, left=True, right=True)
# 图形四周是否显示tick_label
ax.tick_params(labelbottom=True, labeltop=False, labelleft=True, labelright=False)

#ax.tick_params(which='both', width=2)
#ax.tick_params(which='major', length=7)
#ax.tick_params(which='minor', length=4, color='r')


# axis --> 坐标轴
# which --> 主要和次要tick ”both" "major" minor"
ax.tick_params(axis="both", which='both', direction="in") # length=16, width=2, color="turquoise"
ax.tick_params(axis="both", which='both', direction="in")


ax.xaxis.set_major_locator(MultipleLocator(base=0.5))
#ax.xaxis.set_minor_locator(MultipleLocator(base=0.1))
#ax.xaxis.set_minor_locator(AutoMinorLocator(n=5))

ax.yaxis.set_major_locator(MultipleLocator(base=1))
#ax.yaxis.set_minor_locator(AutoMinorLocator(n=2))

# 设置tick的长度和宽度
for xtl in  ax.get_xticklines():
    xtl.set_markersize(2) #length
    xtl.set_markeredgewidth(0.57) #width

for ytl in  ax.get_yticklines():
    ytl.set_markersize(2)
    ytl.set_markeredgewidth(0.57)

# 设置tick_label字体
for xtlabel in ax.get_xticklabels():
    xtlabel.set_fontproperties(tick_font)

for ytlabel in ax.get_yticklabels():
    ytlabel.set_fontproperties(tick_font)


#ax.set_xticks(np.linspace(0,2,5),minor=False)
#ax.set_xticks(np.linspace(0,2,21),minor=True)

#ax.set_yticks(np.linspace(0,9,10),minor=False)
#ax.set_yticks(np.linspace(0,9,19),minor=True)

#ax.minorticks_off()

# tick_label 为公式
#ticks = [-np.pi/2,np.pi/2.]
#labels = [r"$-\frac{\pi}{2}$",r"$\frac{\pi}{2}$"]
#ax.xaxis.set_minor_locator(ticker.FixedLocator(ticks))
#ax.xaxis.set_minor_formatter(ticker.FixedFormatter(labels))

# 设置图形变宽线宽度和颜色
bwith = 0.57
ax.spines['left'].set_color((0,0,0,1))
ax.spines['left'].set_linewidth(bwith)
ax.spines['right'].set_color((0,0,0,1))
ax.spines['right'].set_linewidth(bwith)
ax.spines['top'].set_color((0,0,0,1))
ax.spines['top'].set_linewidth(bwith)
ax.spines['bottom'].set_color((0,0,0,1))
ax.spines['bottom'].set_linewidth(bwith)

#ax.spines['left'].set_color('black')
#ax.spines['bottom'].set_linewidth(bwith)

# 设置图形坐标轴标签和标题字体
ax.set_xlabel('x labelgg',fontdict=font0)  # Add an x-label to the axes.
ax.set_ylabel('y labelgg',fontdict=font0)  # Add a y-label to the axes.
ax.set_title("Simple Plot",fontdict=font0)  # Add a title to the axes.

legend = ax.legend(loc='upper left', bbox_to_anchor=(0.01, 0.99),ncol=1,frameon=True,fancybox=False,
                 facecolor='white',edgecolor='red')  # Add a legend.
frame = legend.get_frame()
frame.set_linewidth(0.57) # 设置图例边框线宽
frame.set_edgecolor("black") # 设置图例边框颜色

plt.tight_layout()
plt.savefig('E:/Users/SubChange/Desktop/dd.tiff',dpi=600)
plt.show()

在这里插入图片描述

2D-twinxy

'''
基本同上,注意两个y轴的设置
'''

import numpy as np

import matplotlib as mpl
import matplotlib.lines as mlines
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D

import matplotlib.font_manager as fm
from matplotlib.ticker import MultipleLocator,AutoMinorLocator,NullLocator


# 1pt = 0.35146mm = 0.035146cm
# 1inch = 2.54cm = 72.27pt
# 图表坐标轴线条粗细最佳为 0.2mm = [0.57pt]
# 线条粗细在0.1mm-0.4mm之间 >>> 0.3mm = [0.85pt]
# 原则上不超过14号字,尽量使用7-12号字,尽量少使用小于6号以下的字体
# 最多见的文字大小推荐使用7、8号字 >> [8pt]

fw = 10/2.54
fh = 8/2.54

mpl.rcParams['font.family'] = 'serif'
mpl.rcParams['font.serif'] = 'Times New Roman'
mpl.rcParams['font.style'] = 'normal'
mpl.rcParams['font.variant'] = 'normal'
mpl.rcParams['font.weight'] = 'normal'
mpl.rcParams['font.stretch'] ='normal'
mpl.rcParams['font.size'] = 9

#mpl.rcParams['xtick.minor.size'] = 10
#mpl.rcParams['xtick.minor.width'] = 2

font0 = {'fontfamily': 'serif',
         'fontname': 'Times New Roman',
         'fontstyle': 'normal',
         'fontvariant': 'normal',
         'fontweight': 'normal',
         'fontstretch': 'normal',
         'fontsize': 9}

tick_font = fm.FontProperties(family='Times New Roman', style='normal', variant='normal', weight='normal',
                           stretch='normal', size=9)
x = np.linspace(0, 2, 100)

# 1pt = 0.35146mm = 0.035146cm
# 1inch = 2.54cm = 72.27pt

#plt.rcParams['xtick.direction'] = 'in'
#plt.rcParams['ytick.direction'] = 'in'
fig = plt.figure(figsize=(fw,fh))
# figsize=(8/2.54,6/2.54),dpi=72
ax = fig.add_subplot(111)  # Create a figure and an axes.

ax.plot(x, x, label='linear',linewidth=0.85,c='r')  # Plot some data on the axes.
ax.plot(x, x**2, label='quadratic',linewidth=0.85,c='g')  # Plot more data on the axes...
ax.plot(x, x**3, label='cubic',linewidth=0.85,c='b')  # ... and some more.


ax.set_xlim([0,2])
ax.set_ylim([0,9])
ax.tick_params(bottom=True, top=True, left=True, right=True)
ax.tick_params(labelbottom=True, labeltop=True, labelleft=True, labelright=True)

#ax.tick_params(which='both', width=2)
#ax.tick_params(which='major', length=7)
#ax.tick_params(which='minor', length=4, color='r')

ax.tick_params(axis="both", which='both', direction="in") # length=16, width=2, color="turquoise"

ax.tick_params(axis="both", which='minor', length=2.1, width=0.5, color="red") # length=16, width=2, color="turquoise"



ax.xaxis.set_major_locator(MultipleLocator(base=0.5))
#ax.xaxis.set_minor_locator(MultipleLocator(base=0.1))
ax.xaxis.set_minor_locator(AutoMinorLocator(n=5))

ax.yaxis.set_major_locator(MultipleLocator(base=1))
ax.yaxis.set_minor_locator(AutoMinorLocator(n=2))

for xtl in  ax.get_xticklines():
    xtl.set_markersize(2.85) #length
    xtl.set_markeredgewidth(0.57)

for ytl in  ax.get_yticklines():
    ytl.set_markersize(2.85)
    ytl.set_markeredgewidth(0.57)


for xtlabel in ax.get_xticklabels():
    xtlabel.set_fontproperties(tick_font)

for ytlabel in ax.get_yticklabels():
    ytlabel.set_fontproperties(tick_font)


#ax.set_xticks(np.linspace(0,2,5),minor=False)
#ax.set_xticks(np.linspace(0,2,21),minor=True)

#ax.set_yticks(np.linspace(0,9,10),minor=False)
#ax.set_yticks(np.linspace(0,9,19),minor=True)

#ax.minorticks_off()

#ticks = [-np.pi/2,np.pi/2.]
#labels = [r"$-\frac{\pi}{2}$",r"$\frac{\pi}{2}$"]
#ax.xaxis.set_minor_locator(ticker.FixedLocator(ticks))
#ax.xaxis.set_minor_formatter(ticker.FixedFormatter(labels))

bwith = 0.57
ax.spines['left'].set_color((0,0,0,1))
ax.spines['left'].set_linewidth(bwith)
#ax.spines['right'].set_color((0,0,0,1))
#ax.spines['right'].set_linewidth(bwith)
#ax.spines['top'].set_color((0,0,0,1))
#ax.spines['top'].set_linewidth(bwith)
ax.spines['bottom'].set_color((0,0,0,1))
ax.spines['bottom'].set_linewidth(bwith)

#ax.spines['left'].set_color('black')
#ax.spines['bottom'].set_linewidth(bwith)

# =====================================================
# 设置第二个y轴
axw = ax.twiny()
axw.set_xlim([0,2])
axw.tick_params(axis="x", which='both', direction="in", color='b')
axw.tick_params(axis="x", which='minor', length=2.1, width=0.5, color="green")
axw.xaxis.set_major_locator(MultipleLocator(base=0.5))
axw.xaxis.set_minor_locator(AutoMinorLocator(n=5))
for xwtl in  axw.get_xticklines():
    xwtl.set_markersize(2.85)
    xwtl.set_markeredgewidth(0.57)

axw.set_xlim([0,4])
axw.set_ylim([0,9])
axw.plot(x, x**3, label='cubic_twinx',linewidth=0.85,c='c')  # Plot more data on the axes...


# 设置第二个x轴
ayw = ax.twinx()
ayw.set_ylim([0,9])
ayw.tick_params(axis="y", which='both', direction="in", color='b')
ayw.tick_params(axis="y", which='minor', length=2.1, width=0.5, color="green")
ayw.yaxis.set_major_locator(MultipleLocator(base=1))
ayw.yaxis.set_minor_locator(AutoMinorLocator(n=2))
for ywtl in  ayw.get_yticklines():
    ywtl.set_markersize(2.85)
    ywtl.set_markeredgewidth(0.57)

ayw.set_xlim([0,2])
ayw.set_ylim([0,18])
ayw.plot(x, x**3, label='cubic_twiny',linewidth=0.85,c='m')  # ... and some more.


ax.set_xlabel('x [mm]',fontdict=font0)  # Add an x-label to the axes.
ax.set_ylabel('y [mm]',fontdict=font0)  # Add a y-label to the axes.
ax.set_title("Simple Plot",fontdict=font0)  # Add a title to the axes.


# 自定义legend
lenline1 = mlines.Line2D([], [], color='r', marker='', linewidth=0.85,
                          markersize=5, label='linear')
lenline2 = mlines.Line2D([], [], color='g', marker='', linewidth=0.85,
                          markersize=5, label='quadratic')
lenline3 = mlines.Line2D([], [], color='b', marker='', linewidth=0.85,
                          markersize=5, label='cubic')
lenline4 = mlines.Line2D([], [], color='c', marker='', linewidth=0.85,
                          markersize=5, label='cubic_twinx')
lenline5 = mlines.Line2D([], [], color='m', marker='', linewidth=0.85,
                          markersize=5, label='cubic_twiny')

legend = ax.legend(handles=[lenline1,lenline2,lenline3,lenline4,lenline5], loc='upper left', bbox_to_anchor=((0.01, 0.99)),ncol=1,frameon=True,fancybox=False,
                 facecolor='white',edgecolor='k',framealpha=1.0)  # Add a legend.
frame = legend.get_frame()
frame.set_linewidth(0.57)
frame.set_edgecolor("black")


plt.tight_layout()
plt.savefig('E:/Users/SubChange/Desktop/dd1.jpg',dpi=600)
plt.show()

在这里插入图片描述

3D

import numpy as np

import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
from mpl_toolkits.mplot3d import art3d

import matplotlib.font_manager as fm
from matplotlib.ticker import MultipleLocator,AutoMinorLocator,NullLocator


# 全局字体参数
mpl.rcParams['font.family'] = 'serif'
mpl.rcParams['font.serif'] = 'Times New Roman'
mpl.rcParams['font.style'] = 'normal'
mpl.rcParams['font.variant'] = 'normal'
mpl.rcParams['font.weight'] = 'normal'
mpl.rcParams['font.stretch'] ='normal'
mpl.rcParams['font.size'] = 9

#mpl.rcParams['xtick.minor.size'] = 10
#mpl.rcParams['xtick.minor.width'] = 2

# 字体1
font0 = {'fontfamily': 'serif',
         'fontname': 'Times New Roman',
         'fontstyle': 'normal',
         'fontvariant': 'normal',
         'fontweight': 'normal',
         'fontstretch': 'normal',
         'fontsize': 9}

# 字体2
tick_font = fm.FontProperties(family='Times New Roman', style='normal', variant='normal', weight='normal',
                           stretch='normal', size=9)


# Fixing random state for reproducibility
np.random.seed(19680801)


'''
因为matplotlib默认不会在3d图上添加边框,这里需要手动添加
'''
def add_borders(ax,edgecolor=(0,0,0,1),linewidth=0.57,scale=1.021):
    #ax.xaxis.pane.set_edgecolor(edgecolor)
    #ax.xaxis.pane.set_linewidth(linewidth)
    #ax.yaxis.pane.set_edgecolor(edgecolor)
    #ax.yaxis.pane.set_linewidth(linewidth)
    #ax.zaxis.pane.set_edgecolor(edgecolor)
    #ax.zaxis.pane.set_linewidth(linewidth)

    #ax.xaxis.pane.set_alpha(1)
    #ax.yaxis.pane.set_alpha(1)
    #ax.zaxis.pane.set_alpha(1)

    #ax.zaxis._axinfo['juggled'] = (1,2,0)
    xlims = ax.get_xlim3d()
    xoffset = (xlims[1] - xlims[0])*scale
    xlims = np.array([xlims[1] - xoffset, xlims[0] + xoffset])
    ylims = ax.get_ylim3d()
    yoffset = (ylims[1] - ylims[0])*scale
    ylims = np.array([ylims[1] - yoffset, ylims[0] + yoffset])
    zlims = ax.get_zlim3d()
    zoffset = (zlims[1] - zlims[0])*scale
    zlims = np.array([zlims[1] - zoffset, zlims[0] + zoffset])

    verts1 = np.array([[xlims[0], ylims[1], zlims[0]],
                       [xlims[0], ylims[0], zlims[0]],
                       [xlims[0], ylims[0], zlims[1]],
                       [xlims[0], ylims[1], zlims[1]]])

    verts2 = np.array([[xlims[1], ylims[1], zlims[0]],
                       [xlims[0], ylims[1], zlims[0]],
                       [xlims[0], ylims[1], zlims[1]],
                       [xlims[1], ylims[1], zlims[1]]])
    #i = np.array([xlims[0], ylims[0], zlims[0]])
    #f = np.array([xlims[0], ylims[0], zlims[1]])
    p = art3d.Line3DCollection([verts1,verts2],facecolor=(1,1,1,0),colors=edgecolor,linewidths=linewidth)
    ax.add_collection3d(p)
    return True



def randrange(n, vmin, vmax):
    """
    Helper function to make an array of random numbers having shape (n, )
    with each number distributed Uniform(vmin, vmax).
    """
    return (vmax - vmin)*np.random.rand(n) + vmin

# 图形大小 单位:厘米
fw = 10/2.54
fh = 10/2.54

fig = plt.figure(figsize=(fw,fh),facecolor=(1.0,1.0,1.0,1.0))
ax = Axes3D(fig,rect=(0,0,1,1),facecolor=(1.0,1.0,1.0,1.0))
# 设置三维图形背景颜色(r,g,b,a)
ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))


n = 100

# For each set of style and range settings, plot n random points in the box
# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].
for m, zlow, zhigh in [('o', -50, -25), ('^', -30, -5)]:
    xs = randrange(n, 23, 32)
    ys = randrange(n, 0, 100)
    zs = randrange(n, zlow, zhigh)
    ax.scatter(xs, ys, zs, s=10, marker=m)

# 设置tick的颜色和线粗
#ax.w_xaxis.line.set_color('red')
#ax.w_yaxis.line.set_color('red')
#ax.w_zaxis.line.set_color('red')
for axis_tmp in [ax.w_xaxis, ax.w_yaxis, ax.w_zaxis]:
    axis_tmp.line.set_linewidth(0.57)
    axis_tmp.line.set_color((1,0,1,1))

# 设置网格颜色和粗细
#ax.xaxis._axinfo["grid"].update({"linewidth":0.5, "color": '#ee0009'})
ax.xaxis._axinfo["grid"]['linewidth'] = 0.5
#ax.xaxis._axinfo["grid"]['color'] = "#ee0009"
ax.xaxis._axinfo["grid"]['linestyle'] = "-"

ax.yaxis._axinfo["grid"]['linewidth'] = 0.5
#ax.yaxis._axinfo["grid"]['color'] = "#ee0009"
ax.yaxis._axinfo["grid"]['linestyle'] = "-"

ax.zaxis._axinfo["grid"]['linewidth'] = 0.5
#ax.zaxis._axinfo["grid"]['color'] = "#ee0009"
ax.zaxis._axinfo["grid"]['linestyle'] = "-"

# 设置tick的颜色的粗细
ax.tick_params(axis="both", which='both', direction="in")
ax.tick_params(axis="both", which='major', length=2.85, width=0.57, color="red")
ax.tick_params(axis="both", which='minor', length=2.1, width=0.5, color="blue")

# ax.tick_params(axis='both', width=10, labelsize=10, pad=0)


ax.set_title('3d title', fontdict=font0, loc='center')

ax.set_xlabel('x [mm]',fontdict=font0)
ax.set_ylabel('y [mm]',fontdict=font0)
ax.set_zlabel('z [mm]',fontdict=font0)

ax.set_xlim([23,32])
ax.set_ylim([0,100])
ax.set_zlim([-50,-5])

ax.xaxis.set_major_locator(MultipleLocator(base=5))
#ax.xaxis.set_minor_locator(MultipleLocator(base=0.1))
ax.xaxis.set_minor_locator(AutoMinorLocator(n=2))

ax.yaxis.set_major_locator(MultipleLocator(base=30))
ax.yaxis.set_minor_locator(AutoMinorLocator(n=2))

ax.zaxis.set_major_locator(MultipleLocator(base=10))
ax.zaxis.set_minor_locator(AutoMinorLocator(n=2))

add_borders(ax,edgecolor=(0,0,0,1),linewidth=0.57) # 添加边框
ax.view_init(elev=20,azim=-80) # 设置视角
plt.tight_layout()
plt.savefig('E:/Users/SubChange/Desktop/dd3d.tiff',dpi=600)
plt.show()

print("over")

在这里插入图片描述

Reference

Python绘制股票日K图(八)绘制大资金折线图 Python绘制股票日K,绘制折线图 阅读详情

相关推荐

python大数据可视化坐标轴的定制与绘制3D图表及统计地图

一、坐标轴的定制 1、概述: 坐标轴及其组成部分对应着matplotlib中一些类的对象︰坐标轴是axis.Axis类的对象,x轴是axis.Xaxis类的对象,y轴是axis.Yaxis类的对象;轴脊是spines.Spine类的对象;刻度是axis.Ticker类的对象。 使用Axes类的对象访问spines属性后,会返回一个OrderedDict类的对象。OrderedDict类是dict的子类,它可以维护添加到字典中键值对的顺序。 2、任意位置添加坐标轴: matplotlib支持向画布的任意位置添

qq_55682472的博客 7682

matplotlib中的label标签

import numpy as np import matplotlib.pyplot as plt X = np.linspace(0,2,100) def func(X): return np.exp(X) y = func(X) plt.rcParams['font.family'] = 'FangSong' plt.plot(X,y,label='指数函数图像') plt.legend(loc='best',fontsize=12) plt中的label参数,其实可以理解为,我们往...

金亮的博客 4867

Matplotlib折线图进阶:从基础绘图到专业级数据可视化定制

数据可视化是数据分析与科学计算的核心环节,其本质是将抽象数据转化为直观图形,以揭示模式、趋势和异常。在Python生态中,matplotlib作为底层绘图库,提供了强大的对象化绘图体系,通过控制Figure、Axes、Axis等核心对象,实现了对图表像素级的精细控制。其技术价值在于平衡了快速原型设计与深度定制能力,是构建复杂、出版级图表的基础。在金融分析、科研绘图、商业报表等应用场景中,折线图因其能清晰展示数据随时间或序列变化的趋势而成为最常用的图表类型之一。本文聚焦于matplotlib折线图的深度定制,

weixin_30546189的博客 424

Matplotlib中的titles(标题)、labels(标签)和legends(图例)

通过上面的介绍,我们应该对这几个术语有了一定了解,那么我们来看看下面的代码i = 1alpha=0.3,i += 1作者:Sami Kohvakka。

deephub 6176

Matplotlib坐标轴刻度与范围设置:从基础到高级的完整指南

在数据可视化中,坐标轴是数据呈现的标尺,其刻度与范围的设置直接影响图表的可读性与专业性。坐标轴范围定义了数据的显示区间,而刻度则决定了数据点的定位与标签展示。通过合理设置坐标轴,可以避免数据被压缩或拉伸,确保数据分布的准确传达。在Python的Matplotlib库中,掌握坐标轴控制是提升图表质量的关键技术,尤其适用于科研图表、商业报告等需要精确对比的场景。本文聚焦于坐标轴刻度与范围的精细化设置,涵盖从基础的手动调整到高级的定位器与格式化器应用,帮助用户解决刻度过密、标签重叠等常见问题,实现从‘能用’到‘好

weixin_34130389的博客 411

Matplotlib进阶指南:从绘图工具到可视化引擎的深度解析

数据可视化是数据分析与科学计算的核心环节,它通过图形化手段将抽象数据转化为直观洞察。其底层原理在于将数据映射为视觉元素,如坐标、颜色和形状,以揭示数据内在的模式与关联。在Python生态中,Matplotlib作为基础且强大的可视化库,其技术价值在于提供了完整的、可编程的图形对象模型,赋予开发者从全局样式到局部元素的像素级控制能力。这种精细控制能力,结合面向对象的编程接口,使得Matplotlib能够胜任从学术论文插图到商业分析仪表板等多种应用场景。本文聚焦于Matplotlib的**核心架构**与**样式

weixin_30407613的博客 408

解决python画图中colorbar设置刻度和标签字体大小

介绍 python很火,因为有各种库的支持,所以功能格外强大。在可视化方面,目前用得较多的是matplotlib. 在基于matplotlib.pyplot画带色标(colorbar)的图时候,往往为了美观和科研用途,需要对colorbar的Ticks(刻度) ,标签(label)和fonddict(字体进行设置)。但是很多初学者都苦于这些东西的设置,因为太麻烦了(别问我怎么知道的)。以下将介绍...

fzl的博客 14万+

Python Matplotlib多Y轴图表绘制:从双轴到四轴的实战指南

在数据可视化中,多轴图表是解决不同量纲、数值范围差异大的数据序列在同一图表中清晰展示的关键技术。其核心原理是通过创建共享X轴但独立的Y轴,实现多变量数据的和谐共存。这项技术的价值在于能有效揭示不同指标间的关联与趋势,避免单一坐标轴导致的信息淹没,广泛应用于金融分析(如股价与成交量)、环境监测(如温度、湿度、气压)以及多维度业务指标对比等场景。本文聚焦于使用Matplotlib的面向对象模式,深入解析通过twinx()方法创建、定位多个Y轴,并系统解决坐标轴对齐、刻度美化、图例合并等工程实践难题,帮助开发者掌

weixin_34161032的博客 353

Matplotlib 常用画图命令总结:使用 Python 在论文中画出一手漂亮的数据图

本文介绍如何使用 Python 语言及 Matplotlib 库来画出各种漂亮的数据图。本文不是一篇详尽的、从简到繁的 Maplotlib 画图教程,而是用各种例子快速直观地让读者上手 Matplotlib 画图中的一些常用的细节操作。本文不对各种数据图作介绍,例如折线图、柱状图等。文中配有效果示意图及代码。本文亦可作为常用画图 API 查询。

Xovee 1万+

Skill-pubfig:Python科研绘图神器,一键生成出版级图表

数据可视化是科研与工程领域的基础技能,其核心在于将复杂数据转化为直观、专业的图表以辅助分析与决策。传统绘图工具如Matplotlib虽功能强大,但代码繁琐、细节调整耗时,难以快速满足学术出版对图表格式的严苛要求。为此,基于Python的科研绘图工具包Skill-pubfig应运而生,它封装了出版级图表的样式规范与常见优化操作,通过预设样式和便捷函数,实现了从“绘图”到“出图”的效率飞跃。该工具包深度整合Matplotlib与Seaborn,提供如`science`、`ieee`等期刊模板,并内置了解决中文显

weixin_34293059的博客 304

【OTDR曲线工具箱】04 批量生成sor文件

软件下载地址:http://120.78.150.214:9999/isora.zip 通过一个测试数据sor文件,批量生成多个测试文件(基于Bellcore GR196及SR-4731标准)。主要考虑哪些问题: 1、sor测试是否符合要求(主要是衰减系数) 2、多个文件的创建时间 3、文件必须随机处理,不要看省去一模一样。 来说说怎么操作的 第一步:选择参考曲线 参考曲线的选择由两种方法:从文件中导入、从曲线库中选择。 其中曲线库分为公共库和个人库两种,平时浏览的sor文件都可以加载到库中。 第二步

夜晚是传说的博客 5266

Matplotlib绘图初步

文章目录绘图基础使用默认设置绘图实例化默认设置图像改变线宽和颜色设置坐标范围设置坐标轴刻度设置刻度标签移动轴线(spines)添加图例标注样本点图形窗口,子图,轴线和刻度图形窗口subplotAxesTicksTick Locators其他种类的图形: 一些例子和练习常见图像散点图条形图等高线Imshow饼图箭头图坐标网格画多个图Multi Plots使用极坐标Polar Axis绘制3D图插入L...

hellocoding的博客 362

cadence——MOS晶体管I-V特性曲线仿真

MOS晶体管I-V特性曲线仿真 目标:使用cadence绘制晶体管的I-V特性曲线(dc仿真) 流程: 新建原理图,将MOS管的栅极电压设为变量Vg,漏极电压设为变量Vd 打开ADEL,点击Variables——Copy From Cellview添加变量;并选择dc仿真,对Vd进行扫描 以Vg作为参变量进行仿真,点击Tools——Parametric Analysis进行设置 选择漏极电流作为输出,进行仿真即可得到I-V特性曲线 ...

skycmq的博客 1万+

Matplotlib字体控制全攻略:从基础设置到中文显示与出版级图表

在数据可视化中,字体控制是决定图表专业度的关键环节,它直接影响到图表的可读性与呈现效果。其原理在于通过配置字体属性来管理文本的渲染,这不仅是美化需求,更是工程实践的一部分,能确保图表在不同媒介(如屏幕、PDF、论文)上清晰一致。掌握字体控制的技术价值在于提升图表质量,避免因字体问题导致分析成果大打折扣,尤其在学术出版、商业报告等场景中至关重要。本文聚焦于matplotlib的字体系统,深入解析字体大小、粗细、样式等基础属性,并攻克中文显示等实战难题,提供从全局配置到局部精细调整的一站式解决方案,帮助读者打造

weixin_34379433的博客 318

Avellaneda & Stoikov’s market-making strategy 工程化处理

前2篇文章详细介绍了AS存货模型的做市策略,这次对于这些公式里面一些希腊字母的取值是如何计算的,如何做工程化并应用到生产环境中做一些说明。这个里面有一些重要参数:很直观,可以直接取值的有:s = current market mid price (中间价,也就是【最佳卖价+最佳买价】/2)q = quantity of assets in inventory of base asset (也就是买入多少价值的股票数量)

weixin_42480337的博客 7067

2021年秋招面经分享·字节跳动【芯片工程师-系统架构】

前言 如果想参考本人背景情况的可见这篇概述 ============================ 正文开始 ============================== 【时间线】 7.29 字节一面 8.4 字节二面 8.11 字节三面 PS:红字表示我当时没答出来的问题,蓝字表示面试官的解答。 面经分享 一面·技术面【1小时5分钟】   面试官京腔重,聊high了所以没时间撕代码了,但是华为应该不会这样。 自我介绍; 介绍一下APB; APB中3个状态的跳转是怎么跳转的; AXI中va

qq_43132308的博客 5610

matplotlib xticks 基于 旋转_咬文嚼字——对matplotlib的文字绘图总结

/导读/我们经常面临在画图时的文字标注,本文从图片、坐标轴、坐标值等层面讲起,对matplotlib的文字绘图功能进行总结说明。Figure和Axes上的文本Matplotlib具有广泛的文本支持,包括对数学表达式的支持、对栅格和矢量输出的TrueType支持、具有任意旋转的换行分隔文本以及Unicode支持。下面通过text,figures,axes,suptitle等案例进行学习...

weixin_39928993的博客 331

微信小程序使用TCP通信

最终目的:在微信小程序内实现对局域网发起TCP通信实现步骤:建立TCP服务 + 小程序发起通信。

Big_YiFeng的博客 5611

Matplotlib绘图全攻略:从Figure/Axes逻辑到实战技巧

数据可视化是数据分析结果传达的关键一环,Python生态中Matplotlib凭借强大的可定制性成为科研与工程领域的核心绘图库。理解其底层逻辑,即Figure画布与Axes坐标区的关系,是掌握所有绘图操作的基础。通过显式的面向对象接口,可以实现从单图到多子图、从基础样式到精细标注的全面控制。在实际工作中,无论是趋势对比、分布探索还是类别分析,合理的图表选型与参数调优都能显著提升信息传递效率。本文围绕Matplotlib的绘图核心流程、常见图表类型、子图布局以及中文乱码等实践问题展开,为读者提供一套从入门到进

weixin_33913332的博客 249

matlab球面投影(二)

matlab球面投影,想做一个全景相机,不知道,要做成啥样,于是在MATLAB先仿真一下,看下是个啥样子 百度别人做的,复制下面的代码到MATLAB的命令串口下,,网上找了张全景图,可以是bmp,jpg,改程序就可以了 回车运行就可以看到结果。 复制下面代码时,下面的中文注释记得删除,MATLAB是会报错的, close all; clear all; clc [x,y,z]=sphere(50); A=imread('a.JPG'); //名字是自己命名的,记得改 B=warp(x,y,-z,

rjszcb的博客 3161

工业产线瑕疵检测:基于 YOLO 的自动化质检系统实战

从工业瑕疵数据集构建到模型训练,从桌面检测界面到产线适用性优化,本文覆盖了一套工业质检系统的完整路线。这个场景的核心评价指标不是最高精度,而是在保证 recall ≥ 0.95 的前提下尽可能压低 false positive——因为漏检的直接成本(客户投诉、质量事故)远高于误报的成本(人工复检)。部署时先设一个偏低的置信度阈值确保覆盖,再通过持续收集人工复检数据来逐步调优。

m0_71589036的博客 65

WCSAxes 非垂直网格与刻度下的 Tick Label 放置修复(astropy 19057)深度解析

本文围绕 astropy 变更记录 [docs/changes/visualization/19057.bugfix.rst](https://link.gitcode.com/i/b60d5052e20ee5d34217223409d58eb2) 中的一条修复声明展开,深入剖析 WCSAxes 在天文图像绘制场景中,当世界坐标系与像素轴不完全对齐(即网格线或刻度与边框不垂直)时,tick lab

gitblog_00645的博客 206

2026华为OD面试题029:勇攀数字高峰

在给定的数字地形图里寻找登山路径,数字代表当前位置的海拔高度。要求从最低海拔出发,不断攀登,最终到达最高山峰。地图保证最低海拔和最高山峰都只有一个。 登山规则: - 路径上的海拔必须严格递增 - 只能向上下左右 4 个方向移动 - 路径必须从最低海拔开始,到最高海拔结束 - 每个地点只能走一次 - 每一步的攀登高度差必须大于 0,且不超过指定值 `K` 输出满足条件的登山路径的数量。

琅嬛福地 113

Matplotlib文字属性全解析:从字体、大小到旋转,打造专业图表

在数据可视化领域,图表不仅是数据的展示,更是信息传达的艺术。其核心原理在于通过视觉元素(如颜色、形状、文字)将抽象数据转化为直观洞察。文字排版作为图表的重要组成部分,直接影响图表的可读性与专业性,是提升数据叙事能力的关键技术。掌握字体管理、字号控制、粗细样式调整及旋转对齐等文字属性,能显著增强图表在不同媒介(如报告、演示文稿、学术出版)中的表现力与适应性。本文聚焦于matplotlib库中的文字属性控制,深入探讨如何通过精细调整字体、大小、粗细、方向与旋转,解决中文乱码、标签重叠等常见问题,并分享跨平台字体

weixin_33672109的博客 382

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

python数据可视化工具 ----matplotlib

【代码】python数据可视化工具 ----matplotlib。

chenliang1038的博客 902

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

Matplotlib三层架构与核心对象解析:从基础绘图到高级定制

数据可视化是数据分析与科学计算中的核心环节,它通过图形化手段将抽象数据转化为直观洞察。其基本原理在于将数据映射为视觉元素,如位置、长度、颜色和形状,以揭示数据中的模式、趋势和异常。掌握高效的可视化工具对于提升数据分析效率和沟通效果具有重要价值,广泛应用于学术研究、商业智能和机器学习模型解释等场景。在Python生态中,Matplotlib作为底层绘图库,提供了从快速原型到出版级图表制作的完整解决方案。理解其基于`Figure`、`Axes`和`Artist`的三层面向对象架构,是解决`ModuleNotFo

weixin_30633405的博客 337

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

上一篇: typora中图片转base64
下一篇: RANSAC点云多平面拟合分割
SubChange
博客等级 码龄9年 104粉丝 9原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值