Zodiac Wang
  • Home
  • Categories
  • Tags
  • Archives

我的Matplotlib绘图模板

Table of Contents

  • 1  Matplotlib 设置全家桶
  • 2  较大单栏图片
  • 3  普通单栏图片
  • 4  双栏图片
  • 5  在 word 中显示比例对比
    • 5.1  在 Word 中粘贴矢量图
  • 6  快速画图初始化代码
  • 7  一个比较好看的 cmap
  • 8  Matplot 3d 柱状图
In [1]:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

Matplotlib 设置全家桶¶

matplotlib 中的 figsize 对应的图片大小并不是分辨率,在 word 中直接体现为粘贴进去之后图片的长宽尺寸有多少英尺,而 dpi 决定了图片的清晰程度。

可用的 rcParams key

可以通过这些 key 调整图片的各种属性

In [2]:
pylab.rcParams.keys()
Out[2]:
KeysView(RcParams({'_internal.classic_mode': False,
          'agg.path.chunksize': 0,
          'animation.avconv_args': [],
          'animation.avconv_path': 'avconv',
          'animation.bitrate': -1,
          'animation.codec': 'h264',
          'animation.convert_args': [],
          'animation.convert_path': 'convert',
          'animation.embed_limit': 20.0,
          'animation.ffmpeg_args': [],
          'animation.ffmpeg_path': 'ffmpeg',
          'animation.frame_format': 'png',
          'animation.html': 'none',
          'animation.html_args': [],
          'animation.writer': 'ffmpeg',
          'axes.autolimit_mode': 'data',
          'axes.axisbelow': 'line',
          'axes.edgecolor': 'k',
          'axes.facecolor': 'w',
          'axes.formatter.limits': [-7, 7],
          'axes.formatter.min_exponent': 0,
          'axes.formatter.offset_threshold': 4,
          'axes.formatter.use_locale': False,
          'axes.formatter.use_mathtext': False,
          'axes.formatter.useoffset': True,
          'axes.grid': False,
          'axes.grid.axis': 'both',
          'axes.grid.which': 'major',
          'axes.hold': None,
          'axes.labelcolor': 'k',
          'axes.labelpad': 4.0,
          'axes.labelsize': 'medium',
          'axes.labelweight': 'normal',
          'axes.linewidth': 0.8,
          'axes.prop_cycle': cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']),
          'axes.spines.bottom': True,
          'axes.spines.left': True,
          'axes.spines.right': True,
          'axes.spines.top': True,
          'axes.titlepad': 6.0,
          'axes.titlesize': 'large',
          'axes.titleweight': 'normal',
          'axes.unicode_minus': True,
          'axes.xmargin': 0.05,
          'axes.ymargin': 0.05,
          'axes3d.grid': True,
          'backend': 'module://ipykernel.pylab.backend_inline',
          'backend.qt4': None,
          'backend.qt5': None,
          'backend_fallback': True,
          'boxplot.bootstrap': None,
          'boxplot.boxprops.color': 'k',
          'boxplot.boxprops.linestyle': '-',
          'boxplot.boxprops.linewidth': 1.0,
          'boxplot.capprops.color': 'k',
          'boxplot.capprops.linestyle': '-',
          'boxplot.capprops.linewidth': 1.0,
          'boxplot.flierprops.color': 'k',
          'boxplot.flierprops.linestyle': 'none',
          'boxplot.flierprops.linewidth': 1.0,
          'boxplot.flierprops.marker': 'o',
          'boxplot.flierprops.markeredgecolor': 'k',
          'boxplot.flierprops.markerfacecolor': 'none',
          'boxplot.flierprops.markersize': 6.0,
          'boxplot.meanline': False,
          'boxplot.meanprops.color': 'C2',
          'boxplot.meanprops.linestyle': '--',
          'boxplot.meanprops.linewidth': 1.0,
          'boxplot.meanprops.marker': '^',
          'boxplot.meanprops.markeredgecolor': 'C2',
          'boxplot.meanprops.markerfacecolor': 'C2',
          'boxplot.meanprops.markersize': 6.0,
          'boxplot.medianprops.color': 'C1',
          'boxplot.medianprops.linestyle': '-',
          'boxplot.medianprops.linewidth': 1.0,
          'boxplot.notch': False,
          'boxplot.patchartist': False,
          'boxplot.showbox': True,
          'boxplot.showcaps': True,
          'boxplot.showfliers': True,
          'boxplot.showmeans': False,
          'boxplot.vertical': True,
          'boxplot.whiskerprops.color': 'k',
          'boxplot.whiskerprops.linestyle': '-',
          'boxplot.whiskerprops.linewidth': 1.0,
          'boxplot.whiskers': 1.5,
          'contour.corner_mask': True,
          'contour.negative_linestyle': 'dashed',
          'datapath': 'c:\\users\\twang\\appdata\\local\\conda\\conda\\envs\\py36\\lib\\site-packages\\matplotlib\\mpl-data',
          'date.autoformatter.day': '%Y-%m-%d',
          'date.autoformatter.hour': '%m-%d %H',
          'date.autoformatter.microsecond': '%M:%S.%f',
          'date.autoformatter.minute': '%d %H:%M',
          'date.autoformatter.month': '%Y-%m',
          'date.autoformatter.second': '%H:%M:%S',
          'date.autoformatter.year': '%Y',
          'docstring.hardcopy': False,
          'errorbar.capsize': 0.0,
          'examples.directory': '',
          'figure.autolayout': False,
          'figure.constrained_layout.h_pad': 0.04167,
          'figure.constrained_layout.hspace': 0.02,
          'figure.constrained_layout.use': False,
          'figure.constrained_layout.w_pad': 0.04167,
          'figure.constrained_layout.wspace': 0.02,
          'figure.dpi': 72.0,
          'figure.edgecolor': (1, 1, 1, 0),
          'figure.facecolor': (1, 1, 1, 0),
          'figure.figsize': [6.0, 4.0],
          'figure.frameon': True,
          'figure.max_open_warning': 20,
          'figure.subplot.bottom': 0.125,
          'figure.subplot.hspace': 0.2,
          'figure.subplot.left': 0.125,
          'figure.subplot.right': 0.9,
          'figure.subplot.top': 0.88,
          'figure.subplot.wspace': 0.2,
          'figure.titlesize': 'large',
          'figure.titleweight': 'normal',
          'font.cursive': ['Apple Chancery',
                           'Textile',
                           'Zapf Chancery',
                           'Sand',
                           'Script MT',
                           'Felipa',
                           'cursive'],
          'font.family': ['sans-serif'],
          'font.fantasy': ['Comic Sans MS',
                           'Chicago',
                           'Charcoal',
                           'ImpactWestern',
                           'Humor Sans',
                           'xkcd',
                           'fantasy'],
          'font.monospace': ['DejaVu Sans Mono',
                             'Bitstream Vera Sans Mono',
                             'Computer Modern Typewriter',
                             'Andale Mono',
                             'Nimbus Mono L',
                             'Courier New',
                             'Courier',
                             'Fixed',
                             'Terminal',
                             'monospace'],
          'font.sans-serif': ['DejaVu Sans',
                              'Bitstream Vera Sans',
                              'Computer Modern Sans Serif',
                              'Lucida Grande',
                              'Verdana',
                              'Geneva',
                              'Lucid',
                              'Arial',
                              'Helvetica',
                              'Avant Garde',
                              'sans-serif'],
          'font.serif': ['DejaVu Serif',
                         'Bitstream Vera Serif',
                         'Computer Modern Roman',
                         'New Century Schoolbook',
                         'Century Schoolbook L',
                         'Utopia',
                         'ITC Bookman',
                         'Bookman',
                         'Nimbus Roman No9 L',
                         'Times New Roman',
                         'Times',
                         'Palatino',
                         'Charter',
                         'serif'],
          'font.size': 10.0,
          'font.stretch': 'normal',
          'font.style': 'normal',
          'font.variant': 'normal',
          'font.weight': 'normal',
          'grid.alpha': 1.0,
          'grid.color': '#b0b0b0',
          'grid.linestyle': '-',
          'grid.linewidth': 0.8,
          'hatch.color': 'k',
          'hatch.linewidth': 1.0,
          'hist.bins': 10,
          'image.aspect': 'equal',
          'image.cmap': 'viridis',
          'image.composite_image': True,
          'image.interpolation': 'nearest',
          'image.lut': 256,
          'image.origin': 'upper',
          'image.resample': True,
          'interactive': True,
          'keymap.all_axes': ['a'],
          'keymap.back': ['left', 'c', 'backspace'],
          'keymap.forward': ['right', 'v'],
          'keymap.fullscreen': ['f', 'ctrl+f'],
          'keymap.grid': ['g'],
          'keymap.grid_minor': ['G'],
          'keymap.home': ['h', 'r', 'home'],
          'keymap.pan': ['p'],
          'keymap.quit': ['ctrl+w', 'cmd+w', 'q'],
          'keymap.quit_all': ['W', 'cmd+W', 'Q'],
          'keymap.save': ['s', 'ctrl+s'],
          'keymap.xscale': ['k', 'L'],
          'keymap.yscale': ['l'],
          'keymap.zoom': ['o'],
          'legend.borderaxespad': 0.5,
          'legend.borderpad': 0.4,
          'legend.columnspacing': 2.0,
          'legend.edgecolor': '0.8',
          'legend.facecolor': 'inherit',
          'legend.fancybox': True,
          'legend.fontsize': 'medium',
          'legend.framealpha': 0.8,
          'legend.frameon': True,
          'legend.handleheight': 0.7,
          'legend.handlelength': 2.0,
          'legend.handletextpad': 0.8,
          'legend.labelspacing': 0.5,
          'legend.loc': 'best',
          'legend.markerscale': 1.0,
          'legend.numpoints': 1,
          'legend.scatterpoints': 1,
          'legend.shadow': False,
          'lines.antialiased': True,
          'lines.color': 'C0',
          'lines.dash_capstyle': 'butt',
          'lines.dash_joinstyle': 'round',
          'lines.dashdot_pattern': [6.4, 1.6, 1.0, 1.6],
          'lines.dashed_pattern': [3.7, 1.6],
          'lines.dotted_pattern': [1.0, 1.65],
          'lines.linestyle': '-',
          'lines.linewidth': 1.5,
          'lines.marker': 'None',
          'lines.markeredgewidth': 1.0,
          'lines.markersize': 6.0,
          'lines.scale_dashes': True,
          'lines.solid_capstyle': 'projecting',
          'lines.solid_joinstyle': 'round',
          'markers.fillstyle': 'full',
          'mathtext.bf': 'sans:bold',
          'mathtext.cal': 'cursive',
          'mathtext.default': 'it',
          'mathtext.fallback_to_cm': True,
          'mathtext.fontset': 'dejavusans',
          'mathtext.it': 'sans:italic',
          'mathtext.rm': 'sans',
          'mathtext.sf': 'sans',
          'mathtext.tt': 'monospace',
          'patch.antialiased': True,
          'patch.edgecolor': 'k',
          'patch.facecolor': 'C0',
          'patch.force_edgecolor': False,
          'patch.linewidth': 1.0,
          'path.effects': [],
          'path.simplify': True,
          'path.simplify_threshold': 0.1111111111111111,
          'path.sketch': None,
          'path.snap': True,
          'pdf.compression': 6,
          'pdf.fonttype': 3,
          'pdf.inheritcolor': False,
          'pdf.use14corefonts': False,
          'pgf.debug': False,
          'pgf.preamble': [],
          'pgf.rcfonts': True,
          'pgf.texsystem': 'xelatex',
          'polaraxes.grid': True,
          'ps.distiller.res': 6000,
          'ps.fonttype': 3,
          'ps.papersize': 'letter',
          'ps.useafm': False,
          'ps.usedistiller': False,
          'savefig.bbox': None,
          'savefig.directory': '~',
          'savefig.dpi': 'figure',
          'savefig.edgecolor': 'w',
          'savefig.facecolor': 'w',
          'savefig.format': 'png',
          'savefig.frameon': True,
          'savefig.jpeg_quality': 95,
          'savefig.orientation': 'portrait',
          'savefig.pad_inches': 0.1,
          'savefig.transparent': False,
          'scatter.marker': 'o',
          'svg.fonttype': 'path',
          'svg.hashsalt': None,
          'svg.image_inline': True,
          'text.antialiased': True,
          'text.color': 'k',
          'text.hinting': 'auto',
          'text.hinting_factor': 8,
          'text.latex.preamble': [],
          'text.latex.preview': False,
          'text.latex.unicode': False,
          'text.usetex': False,
          'timezone': 'UTC',
          'tk.window_focus': False,
          'toolbar': 'toolbar2',
          'verbose.fileo': 'sys.stdout',
          'verbose.level': 'silent',
          'webagg.address': '127.0.0.1',
          'webagg.open_in_browser': True,
          'webagg.port': 8988,
          'webagg.port_retries': 50,
          'xtick.alignment': 'center',
          'xtick.bottom': True,
          'xtick.color': 'k',
          'xtick.direction': 'out',
          'xtick.labelbottom': True,
          'xtick.labelsize': 'medium',
          'xtick.labeltop': False,
          'xtick.major.bottom': True,
          'xtick.major.pad': 3.5,
          'xtick.major.size': 3.5,
          'xtick.major.top': True,
          'xtick.major.width': 0.8,
          'xtick.minor.bottom': True,
          'xtick.minor.pad': 3.4,
          'xtick.minor.size': 2.0,
          'xtick.minor.top': True,
          'xtick.minor.visible': False,
          'xtick.minor.width': 0.6,
          'xtick.top': False,
          'ytick.alignment': 'center_baseline',
          'ytick.color': 'k',
          'ytick.direction': 'out',
          'ytick.labelleft': True,
          'ytick.labelright': False,
          'ytick.labelsize': 'medium',
          'ytick.left': True,
          'ytick.major.left': True,
          'ytick.major.pad': 3.5,
          'ytick.major.right': True,
          'ytick.major.size': 3.5,
          'ytick.major.width': 0.8,
          'ytick.minor.left': True,
          'ytick.minor.pad': 3.4,
          'ytick.minor.right': True,
          'ytick.minor.size': 2.0,
          'ytick.minor.visible': False,
          'ytick.minor.width': 0.6,
          'ytick.right': False}))

设置中文字体,解决Matplotlib不能显示中文的问题

In [3]:
font_name = "SimHei"
# 指定字体,实际上相当于修改 matplotlibrc 文件 只不过这样做是暂时的 下次失效
matplotlib.rcParams['font.family'] = font_name
matplotlib.rcParams['axes.unicode_minus'] = False  # 正确显示负号,防止变成方框

matplotlib 中的 figsize 图片大小,对应的是粘贴到 word 里的宽高,单位为英寸

1英寸=2.54厘米

使用比例 宽:高 = 4:3

论文写作指南推荐的三种图片比例

原始厘米     转换英寸     取整英寸
6.67 * 5.00   2.62 * 1.95   2.6 * 1.95    适合双栏
9.00 * 6.75   3.54 * 2.66   3.5 * 2.625   适合普通单栏
13.5 * 9.00   5.31 * 3.54   5.4 * 4.05    适合较大图片

我下面的模板没有按照这个尺寸

较大单栏图片¶

In [4]:
# 绘图参数,一次搞定
params = {
    'font.size': '10',
    'axes.titlesize': '10',
    'axes.labelsize': '10',
    'xtick.labelsize': '10',
    'ytick.labelsize': '10',
    'lines.linewidth': '1',
    'legend.fontsize': '10',
    'axes.labelpad': '3.0',
    'figure.figsize': '6, 4',
}
pylab.rcParams.update(params)
In [5]:
t = np.linspace(0, 10, 100)
# y = [47.0567, 50.1325, 50.3974, 46.4238, 51.5894, 50.1325, 47.2185, 45.7616, 54.7682, 49.7351]
y = np.sin(t)
y_ = y + 0.5*(np.random.random(t.shape[0])-0.5)

fig, ax = plt.subplots()

ax.plot(t, y, label=u"真实值")
ax.plot(t, y_, label=u'跟踪值')

ax.set_title(u'跟踪效果')
ax.set_xlabel(u'时间(秒)')
ax.set_ylabel(u'高度(米)')
ax.set_xlim(0, 10)
ax.set_ylim(-1.2, 1.2)
ax.set_xticks(np.arange(1, 11))
ax.legend(loc=2)  # upper left corner
ax.minorticks_on()  # 显示小刻度
ax.tick_params(which='both', direction='in',
               bottom=True, top=True, left=True, right=True)  # 控制坐标轴显示与否以及方向, which选择主次坐标刻度
ax.grid(color='k', alpha=0.5, linestyle='dashed', linewidth=0.5)
fig.tight_layout()
# plt.grid(True)
plt.savefig("data/test1.png", bbox_inches='tight', dpi=500)
plt.savefig("data/test1.pdf", bbox_inches='tight')
plt.savefig("data/test1.svg", bbox_inches='tight')

普通单栏图片¶

In [6]:
# 绘图参数,一次搞定
params = {
    'font.size': '8',
    'axes.titlesize': '8',
    'axes.labelsize': '8',
    'xtick.labelsize': '8',
    'ytick.labelsize': '8',
    'lines.linewidth': '1',
    'legend.fontsize': '8',
    'axes.labelpad': '3.0',
    'figure.figsize': '4.5, 3',
}
pylab.rcParams.update(params)
In [7]:
t = np.linspace(0, 10, 100)
# y = [47.0567, 50.1325, 50.3974, 46.4238, 51.5894, 50.1325, 47.2185, 45.7616, 54.7682, 49.7351]
y = np.sin(t)
y_ = y + 0.5*(np.random.random(t.shape[0])-0.5)

fig, ax = plt.subplots()

ax.plot(t, y, label=u"真实值")
ax.plot(t, y_, label=u'跟踪值')

ax.set_title(u'跟踪效果')
ax.set_xlabel(u'时间(秒)')
ax.set_ylabel(u'高度(米)')
ax.set_xlim(0, 10)
ax.set_ylim(-1.2, 1.2)
ax.set_xticks(np.arange(1, 11))
ax.legend(loc=2)  # upper left corner
ax.minorticks_on()  # 显示小刻度
ax.tick_params(which='both', direction='in',
               bottom=True, top=True, left=True, right=True)  # 控制坐标轴显示与否以及方向, which选择主次坐标刻度
ax.grid(color='k', alpha=0.5, linestyle='dashed', linewidth=0.5)
fig.tight_layout()
# plt.grid(True)
plt.savefig("data/test2.png", bbox_inches='tight', dpi=500)
plt.savefig("data/test2.pdf", bbox_inches='tight')
plt.savefig("data/test2.svg", bbox_inches='tight')

双栏图片¶

In [8]:
# 绘图参数,一次搞定
params = {
    'font.size': '8',
    'axes.titlesize': '8',
    'axes.labelsize': '8',
    'xtick.labelsize': '8',
    'ytick.labelsize': '8',
    'lines.linewidth': '1',
    'legend.fontsize': '7',
    'axes.labelpad': '2.0',
    'figure.figsize': '3, 2',
}
pylab.rcParams.update(params)
In [9]:
t = np.linspace(0, 10, 100)
# y = [47.0567, 50.1325, 50.3974, 46.4238, 51.5894, 50.1325, 47.2185, 45.7616, 54.7682, 49.7351]
y = np.sin(t)
y_ = y + 0.5*(np.random.random(t.shape[0])-0.5)

fig, ax = plt.subplots()

ax.plot(t, y, label=u"真实值")
ax.plot(t, y_, label=u'跟踪值')

ax.set_title(u'跟踪效果')
ax.set_xlabel(u'时间(秒)')
ax.set_ylabel(u'高度(米)')
ax.set_xlim(0, 10)
ax.set_ylim(-1.2, 1.2)
ax.set_xticks(np.arange(1, 11))
ax.legend(loc=2)  # upper left corner
ax.minorticks_on()  # 显示小刻度
ax.tick_params(which='both', direction='in',
               bottom=True, top=True, left=True, right=True)  # 控制坐标轴显示与否以及方向, which选择主次坐标刻度
ax.grid(color='k', alpha=0.5, linestyle='dashed', linewidth=0.5)
fig.tight_layout()
# plt.grid(True)
plt.savefig("data/test3.png", bbox_inches='tight', dpi=500)
plt.savefig("data/test3.pdf", bbox_inches='tight')
plt.savefig("data/test3.svg", bbox_inches='tight')

在 word 中显示比例对比¶

直接使用png文件粘贴,宽度在word内分别按比例调整为 13 9 6.67厘米


在 Word 中粘贴矢量图¶

  • 场景1 代码生成

Word 中无法粘贴 eps 和 pdf 图片,Python 或 matlab 输出的 svg 文件本身可以直接粘贴到 Word 中,但这样 Word 文件另存为 pdf 时会存在线条加粗的情况,具体原因未知。替代方法是,将 svg 粘贴至 ppt 中,复制之后按快捷键 Ctrl + Alt + V 选择性粘贴,粘贴转换为 图片(增强性图元文件)即 emf 文件,再将该图片粘贴至 Word 中即可。不过粘贴为 emf 文件过程中,图片的尺寸(宽、高厘米数)会发生一点变化,既然是矢量图,都是能缩放的,大小也就无所谓了。这样粘贴到 Word 中的就是矢量图了

  • 场景2 手动绘制

使用 PPT 或 Visio 绘图,复制选择性粘贴为 图片(增强性图元文件),之后再粘贴到 Word 中。

转换为增强性图元文件会导致图片尺寸的变化(放大一些),不影响比例,且可能导致某些线条的粗细由于渲染问题出现变化

快速画图初始化代码¶

In [10]:
fig, ax = plt.subplots()
# ax.set_aspect('equal','box') # 设置坐标轴比例

t = np.linspace(0, 2*np.pi, 50, endpoint=False)
sins = np.sin(t)
coss = np.cos(t)

ax.plot(t, sins, 'r', alpha=0.5, lw=0.5, ls='-', marker='+', label='sin')
ax.plot(t, coss, 'g', alpha=0.5, lw=0.5, ls='-', marker='+', label='cos')

ax.set_title('title')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_ylim([-1.5, 1.5])
ax.set_xlim([-2, 8])
# xticks = [1, 2, 3, 4, 5]
# ax.set_xticks(xticks)
# ax.set_xticklabels([r'$\alpha$', r'$\beta$', r'$\gamma$', r'$\delta$', r'$\epsilon$'], fontsize=18)
# yticks = [0, 1, 2, 3, 4]
# ax.set_yticks(yticks)
# ax.set_yticklabels(["$%.1f$" % y for y in yticks], fontsize=18); # use LaTeX formatted labels
# ax.set_yscale("log")
# ax.xaxis.labelpad = 5
# ax.yaxis.labelpad = 5
ax.legend(loc='lower right')
ax.minorticks_on()  # 显示小刻度
ax.tick_params(which='both', direction='in',
               bottom=True, top=True, left=True, right=True)  # 控制坐标轴显示与否以及方向, which选择主次坐标刻度
# ax.spines['right'].set_color("none") # 取消右边坐标轴的显示
ax.grid(color='k', alpha=0.5, linestyle='dashed', linewidth=0.5)

# fig.subplots_adjust(left=0.15, right=.9, bottom=0.1, top=0.9)  # 调整绘图在整个画布中的位置
fig.savefig("data/test4.png", bbox_inches='tight', dpi=500)
fig.savefig("data/test4.pdf", bbox_inches='tight')
fig.savefig("data/test4.svg", bbox_inches='tight')
plt.show()

一个比较好看的 cmap¶

In [11]:
t = np.linspace(0, 2*np.pi, 1000, endpoint=True)
y = np.sin(t)
cs = matplotlib.cm.rainbow(np.linspace(0, 1, 1000))

plt.scatter(t, y, color=cs, alpha=0.5)
Out[11]:
<matplotlib.collections.PathCollection at 0x22bbc9550f0>

Matplot 3d 柱状图¶

axes.bar3d(x, y, z, dx, dy, dz, color=None, zsort='average', shade=True, *args, **kwargs)

注意进行 ravel 操作

In [12]:
fig = plt.figure(figsize=(16, 6))
ax1 = fig.add_subplot(121, projection='3d')
ax2 = fig.add_subplot(122, projection='3d')

_xx, _yy = np.meshgrid(np.arange(4), np.arange(5))
x, y = _xx.ravel(), _yy.ravel()

top = x + y
z = np.zeros_like(top)
dx = dy = 0.5

ax1.bar3d(x, y, z, dx, dy, top, shade=True)
ax1.set_title('Shaded')

ax2.bar3d(x, y, z, dx, dy, top, shade=False)
ax2.set_title('Not Shaded')

for e in (ax1, ax2):
    e.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
    e.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
    e.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))

plt.show()

3d plot 视角调整

view_init(elev=None, azim=None)

Set the elevation and azimuth of the axes. This can be used to rotate the axes programatically. ‘elev’ stores the elevation angle in the z plane. ‘azim’ stores the azimuth angle in the x,y plane. if elev or azim are None (default), then the initial value is used which was specified in the Axes3D constructor.

elev 是 z 平面的角度 azim 是 xy 平面角度

实际上可以在 add_subplot 的时候指定角度

ax = fig.add_axes([0, 0, .95, 1], elev=48, azim=134, projection='3d')
In [13]:
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')

_xx, _yy = np.meshgrid(np.arange(4), np.arange(5))
x, y = _xx.ravel(), _yy.ravel()

top = x + y
z = np.zeros_like(top)
dx = dy = 0.5

ax.bar3d(x, y, z, dx, dy, top, shade=True)
ax.set_title('Shaded')

for e in (ax,):
    e.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
    e.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
    e.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))

ax1.view_init(20, 320)  # 调整角度
plt.show()

  • « Windows系统Matplotlib无法显示中文解决办法
  • 一个数据处理pipeline »

Published

1 7, 2019

Category

posts

Tags

  • Matplotlib 10

Contact

  • Zodiac Wang - A Fantastic Learner
  • Powered by Pelican. Theme: Elegant