matplotlib

  • matplotlib는 Python에서 차트나 플롯을 시각화하는 패키지
  • 홈페이지

  • matplotlib 내부에 pylab 서브패키지는 matlab 수치해석 소프트웨어 시각화 명령을 그대로 사용!

  • ipython에선 %matplotlib inline을 통해 바로 그림을 볼 수 있음

In [2]:
import matplotlib as mpl
import matplotlib.pylab as plt
import numpy as np
import pandas as pd
import matplotlib.ticker as tkr


%matplotlib inline

In [8]:
# plt의 내부 메소드
dir(plt)


Out[8]:
['ALLOW_THREADS',
 'Annotation',
 'Arrow',
 'Artist',
 'AutoLocator',
 'Axes',
 'AxisError',
 'BUFSIZE',
 'Button',
 'CLIP',
 'Circle',
 'ComplexWarning',
 'DAILY',
 'DataSource',
 'DateFormatter',
 'DateLocator',
 'DayLocator',
 'ERR_CALL',
 'ERR_DEFAULT',
 'ERR_IGNORE',
 'ERR_LOG',
 'ERR_PRINT',
 'ERR_RAISE',
 'ERR_WARN',
 'FLOATING_POINT_SUPPORT',
 'FPE_DIVIDEBYZERO',
 'FPE_INVALID',
 'FPE_OVERFLOW',
 'FPE_UNDERFLOW',
 'FR',
 'False_',
 'Figure',
 'FigureCanvasBase',
 'FixedFormatter',
 'FixedLocator',
 'FormatStrFormatter',
 'Formatter',
 'FuncFormatter',
 'GridSpec',
 'HOURLY',
 'HourLocator',
 'IndexDateFormatter',
 'IndexLocator',
 'Inf',
 'Infinity',
 'LinAlgError',
 'Line2D',
 'LinearLocator',
 'Locator',
 'LogFormatter',
 'LogFormatterExponent',
 'LogFormatterMathtext',
 'LogLocator',
 'MAXDIMS',
 'MAY_SHARE_BOUNDS',
 'MAY_SHARE_EXACT',
 'MINUTELY',
 'MO',
 'MONTHLY',
 'MachAr',
 'MaxNLocator',
 'MinuteLocator',
 'ModuleDeprecationWarning',
 'MonthLocator',
 'MultipleLocator',
 'NAN',
 'NINF',
 'NZERO',
 'NaN',
 'Normalize',
 'NullFormatter',
 'NullLocator',
 'PINF',
 'PZERO',
 'PackageLoader',
 'PolarAxes',
 'Polygon',
 'RAISE',
 'RRuleLocator',
 'RankWarning',
 'Rectangle',
 'SA',
 'SECONDLY',
 'SHIFT_DIVIDEBYZERO',
 'SHIFT_INVALID',
 'SHIFT_OVERFLOW',
 'SHIFT_UNDERFLOW',
 'SU',
 'ScalarFormatter',
 'ScalarType',
 'SecondLocator',
 'Slider',
 'Subplot',
 'SubplotTool',
 'TH',
 'TU',
 'Text',
 'TickHelper',
 'TooHardError',
 'True_',
 'UFUNC_BUFSIZE_DEFAULT',
 'UFUNC_PYVALS_NAME',
 'VisibleDeprecationWarning',
 'WE',
 'WEEKLY',
 'WRAP',
 'WeekdayLocator',
 'Widget',
 'YEARLY',
 'YearLocator',
 '__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 '__version__',
 'absolute',
 'absolute_import',
 'acorr',
 'add',
 'add_docstring',
 'add_newdoc',
 'add_newdoc_ufunc',
 'add_newdocs',
 'alen',
 'all',
 'allclose',
 'alltrue',
 'amap',
 'amax',
 'amin',
 'angle',
 'angle_spectrum',
 'annotate',
 'any',
 'append',
 'apply_along_axis',
 'apply_over_axes',
 'arange',
 'arccos',
 'arccosh',
 'arcsin',
 'arcsinh',
 'arctan',
 'arctan2',
 'arctanh',
 'argmax',
 'argmin',
 'argpartition',
 'argsort',
 'argwhere',
 'around',
 'array',
 'array2string',
 'array_equal',
 'array_equiv',
 'array_repr',
 'array_split',
 'array_str',
 'arrow',
 'asanyarray',
 'asarray',
 'asarray_chkfinite',
 'ascontiguousarray',
 'asfarray',
 'asfortranarray',
 'asmatrix',
 'asscalar',
 'atleast_1d',
 'atleast_2d',
 'atleast_3d',
 'autoscale',
 'autumn',
 'average',
 'axes',
 'axhline',
 'axhspan',
 'axis',
 'axvline',
 'axvspan',
 'bar',
 'barbs',
 'barh',
 'bartlett',
 'base_repr',
 'bench',
 'beta',
 'binary_repr',
 'bincount',
 'binomial',
 'bitwise_and',
 'bitwise_not',
 'bitwise_or',
 'bitwise_xor',
 'bivariate_normal',
 'blackman',
 'block',
 'bmat',
 'bone',
 'bool8',
 'bool_',
 'box',
 'boxplot',
 'broadcast',
 'broadcast_arrays',
 'broadcast_to',
 'broken_barh',
 'busday_count',
 'busday_offset',
 'busdaycalendar',
 'byte',
 'byte_bounds',
 'bytes',
 'bytes0',
 'bytes_',
 'c_',
 'can_cast',
 'cast',
 'cbook',
 'cbrt',
 'cdouble',
 'ceil',
 'center_matrix',
 'cfloat',
 'char',
 'character',
 'chararray',
 'chisquare',
 'choice',
 'cholesky',
 'choose',
 'cla',
 'clabel',
 'clf',
 'clim',
 'clip',
 'clongdouble',
 'clongfloat',
 'close',
 'cm',
 'cohere',
 'colorbar',
 'colormaps',
 'colors',
 'column_stack',
 'common_type',
 'compare_chararrays',
 'complex128',
 'complex256',
 'complex64',
 'complex_',
 'complexfloating',
 'compress',
 'concatenate',
 'cond',
 'conj',
 'conjugate',
 'connect',
 'contour',
 'contourf',
 'convolve',
 'cool',
 'copper',
 'copy',
 'copysign',
 'copyto',
 'corrcoef',
 'correlate',
 'cos',
 'cosh',
 'count_nonzero',
 'cov',
 'cross',
 'csd',
 'csingle',
 'csv2rec',
 'ctypeslib',
 'cumprod',
 'cumproduct',
 'cumsum',
 'cycler',
 'date2num',
 'datestr2num',
 'datetime',
 'datetime64',
 'datetime_as_string',
 'datetime_data',
 'dedent',
 'deg2rad',
 'degrees',
 'delaxes',
 'delete',
 'demean',
 'deprecate',
 'deprecate_with_doc',
 'deprecated',
 'det',
 'detrend',
 'detrend_linear',
 'detrend_mean',
 'detrend_none',
 'diag',
 'diag_indices',
 'diag_indices_from',
 'diagflat',
 'diagonal',
 'diff',
 'digitize',
 'dirichlet',
 'disconnect',
 'disp',
 'dist',
 'dist_point_to_segment',
 'distances_along_curve',
 'divide',
 'division',
 'divmod',
 'docstring',
 'dot',
 'double',
 'drange',
 'draw',
 'draw_all',
 'draw_if_interactive',
 'dsplit',
 'dstack',
 'dtype',
 'e',
 'ediff1d',
 'eig',
 'eigh',
 'eigvals',
 'eigvalsh',
 'einsum',
 'einsum_path',
 'emath',
 'empty',
 'empty_like',
 'entropy',
 'epoch2num',
 'equal',
 'errorbar',
 'errstate',
 'euler_gamma',
 'eventplot',
 'exception_to_str',
 'exp',
 'exp2',
 'exp_safe',
 'expand_dims',
 'expm1',
 'exponential',
 'extract',
 'eye',
 'f',
 'fabs',
 'fastCopyAndTranspose',
 'fft',
 'fft2',
 'fftfreq',
 'fftn',
 'fftpack',
 'fftpack_lite',
 'fftshift',
 'fftsurr',
 'figaspect',
 'figimage',
 'figlegend',
 'fignum_exists',
 'figtext',
 'figure',
 'fill',
 'fill_between',
 'fill_betweenx',
 'fill_diagonal',
 'find',
 'find_common_type',
 'findobj',
 'finfo',
 'fix',
 'flag',
 'flatiter',
 'flatnonzero',
 'flatten',
 'flexible',
 'flip',
 'fliplr',
 'flipud',
 'float128',
 'float16',
 'float32',
 'float64',
 'float_',
 'float_power',
 'floating',
 'floor',
 'floor_divide',
 'fmax',
 'fmin',
 'fmod',
 'format_parser',
 'frange',
 'frexp',
 'frombuffer',
 'fromfile',
 'fromfunction',
 'fromiter',
 'frompyfunc',
 'fromregex',
 'fromstring',
 'full',
 'full_like',
 'fv',
 'gamma',
 'gca',
 'gcf',
 'gci',
 'generic',
 'genfromtxt',
 'geometric',
 'geomspace',
 'get',
 'get_array_wrap',
 'get_backend',
 'get_cmap',
 'get_current_fig_manager',
 'get_figlabels',
 'get_fignums',
 'get_include',
 'get_plot_commands',
 'get_printoptions',
 'get_scale_docs',
 'get_scale_names',
 'get_sparse_matrix',
 'get_state',
 'get_xyz_where',
 'getbufsize',
 'geterr',
 'geterrcall',
 'geterrobj',
 'getp',
 'ginput',
 'gradient',
 'gray',
 'greater',
 'greater_equal',
 'grid',
 'griddata',
 'gumbel',
 'half',
 'hamming',
 'hanning',
 'heaviside',
 'helper',
 'hexbin',
 'hfft',
 'hist',
 'hist2d',
 'histogram',
 'histogram2d',
 'histogramdd',
 'hlines',
 'hold',
 'hot',
 'hsplit',
 'hstack',
 'hsv',
 'hypergeometric',
 'hypot',
 'i0',
 'identity',
 'ifft',
 'ifft2',
 'ifftn',
 'ifftshift',
 'ihfft',
 'iinfo',
 'imag',
 'imread',
 'imsave',
 'imshow',
 'in1d',
 'index_exp',
 'indices',
 'inexact',
 'inf',
 'inferno',
 'info',
 'infty',
 'inner',
 'insert',
 'inside_poly',
 'install_repl_displayhook',
 'int0',
 'int16',
 'int32',
 'int64',
 'int8',
 'int_',
 'int_asbuffer',
 'intc',
 'integer',
 'interactive',
 'interp',
 'intersect1d',
 'intp',
 'inv',
 'invert',
 'ioff',
 'ion',
 'ipmt',
 'irfft',
 'irfft2',
 'irfftn',
 'irr',
 'is_busday',
 'is_closed_polygon',
 'is_numlike',
 'is_string_like',
 'isclose',
 'iscomplex',
 'iscomplexobj',
 'isfinite',
 'isfortran',
 'ishold',
 'isin',
 'isinf',
 'isinteractive',
 'isnan',
 'isnat',
 'isneginf',
 'isposinf',
 'ispower2',
 'isreal',
 'isrealobj',
 'isscalar',
 'issctype',
 'issubclass_',
 'issubdtype',
 'issubsctype',
 'isvector',
 'iterable',
 'ix_',
 'jet',
 'kaiser',
 'kron',
 'l1norm',
 'l2norm',
 'lapack_lite',
 'laplace',
 'ldexp',
 'left_shift',
 'legend',
 'less',
 'less_equal',
 'lexsort',
 'linalg',
 'linspace',
 'little_endian',
 'load',
 'loads',
 'loadtxt',
 'locator_params',
 'log',
 'log10',
 'log1p',
 'log2',
 'logaddexp',
 'logaddexp2',
 'logical_and',
 'logical_not',
 'logical_or',
 'logical_xor',
 'logistic',
 'loglog',
 'lognormal',
 'logseries',
 'logspace',
 'long',
 'longcomplex',
 'longdouble',
 'longest_contiguous_ones',
 'longest_ones',
 'longfloat',
 'longlong',
 'lookfor',
 'lstsq',
 'ma',
 'mafromtxt',
 'magma',
 'magnitude_spectrum',
 'margins',
 'mask_indices',
 'mat',
 'math',
 'matmul',
 'matplotlib',
 'matrix',
 'matrix_power',
 'matrix_rank',
 'matshow',
 'maximum',
 'maximum_sctype',
 'may_share_memory',
 'mean',
 'median',
 'memmap',
 'meshgrid',
 'mgrid',
 'min_scalar_type',
 'minimum',
 'minorticks_off',
 'minorticks_on',
 'mintypecode',
 'mirr',
 'mlab',
 'mod',
 'modf',
 'movavg',
 'moveaxis',
 'mpl',
 'msort',
 'multi_dot',
 'multinomial',
 'multiply',
 'multivariate_normal',
 'mx2num',
 'nan',
 'nan_to_num',
 'nanargmax',
 'nanargmin',
 'nancumprod',
 'nancumsum',
 'nanmax',
 'nanmean',
 'nanmedian',
 'nanmin',
 'nanpercentile',
 'nanprod',
 'nanstd',
 'nansum',
 'nanvar',
 'nbytes',
 'ndarray',
 'ndenumerate',
 'ndfromtxt',
 'ndim',
 'ndindex',
 'nditer',
 'negative',
 'negative_binomial',
 'nested_iters',
 'new_figure_manager',
 'newaxis',
 'nextafter',
 'nipy_spectral',
 'noncentral_chisquare',
 'noncentral_f',
 'nonzero',
 'norm',
 'norm_flat',
 'normal',
 'normpdf',
 'not_equal',
 'np',
 'nper',
 'npv',
 'num2date',
 'num2epoch',
 'number',
 'obj2sctype',
 'object0',
 'object_',
 'ogrid',
 'ones',
 'ones_like',
 'outer',
 'over',
 'packbits',
 'pad',
 'pareto',
 'partition',
 'path_length',
 'pause',
 'pcolor',
 'pcolormesh',
 'percentile',
 'permutation',
 'phase_spectrum',
 'pi',
 'pie',
 'piecewise',
 'pink',
 'pinv',
 'pkgload',
 'place',
 'plasma',
 'plot',
 'plot_date',
 'plotfile',
 'plotting',
 'plt',
 'pmt',
 'poisson',
 'polar',
 'poly',
 'poly1d',
 'poly_below',
 'poly_between',
 'polyadd',
 'polyder',
 'polydiv',
 'polyfit',
 'polyint',
 'polymul',
 'polysub',
 'polyval',
 'positive',
 'power',
 'ppmt',
 'prctile',
 'prctile_rank',
 'print_function',
 'prism',
 'prod',
 'product',
 'promote_types',
 'psd',
 'ptp',
 'put',
 'putmask',
 'pv',
 'pylab_setup',
 'qr',
 'quiver',
 'quiverkey',
 'r_',
 'rad2deg',
 'radians',
 'rand',
 'randint',
 'randn',
 'random',
 'random_integers',
 'random_sample',
 'ranf',
 'rank',
 'rate',
 'ravel',
 'ravel_multi_index',
 'rayleigh',
 'rc',
 'rcParams',
 'rcParamsDefault',
 'rc_context',
 'rcdefaults',
 'real',
 'real_if_close',
 'rec',
 'rec2csv',
 'rec_append_fields',
 'rec_drop_fields',
 'rec_join',
 'recarray',
 'recfromcsv',
 'recfromtxt',
 'reciprocal',
 'record',
 'register_cmap',
 'relativedelta',
 'remainder',
 'repeat',
 'require',
 'reshape',
 'resize',
 'result_type',
 'rfft',
 'rfft2',
 'rfftfreq',
 'rfftn',
 'rgrids',
 'right_shift',
 'rint',
 'rk4',
 'rms_flat',
 'roll',
 'rollaxis',
 'roots',
 'rot90',
 'round_',
 'row_stack',
 'rrule',
 's_',
 'safe_eval',
 'sample',
 'save',
 'savefig',
 'savetxt',
 'savez',
 'savez_compressed',
 'sca',
 'scatter',
 'sci',
 'sctype2char',
 'sctypeDict',
 'sctypeNA',
 'sctypes',
 'searchsorted',
 'seed',
 'segments_intersect',
 'select',
 'semilogx',
 'semilogy',
 'set_cmap',
 'set_numeric_ops',
 'set_printoptions',
 'set_state',
 'set_string_function',
 'setbufsize',
 'setdiff1d',
 'seterr',
 'seterrcall',
 'seterrobj',
 'setp',
 'setxor1d',
 'shape',
 'shares_memory',
 'short',
 'show',
 'show_config',
 'shuffle',
 'sign',
 'signbit',
 'signedinteger',
 'silent_list',
 'sin',
 'sinc',
 'single',
 'singlecomplex',
 'sinh',
 'six',
 'size',
 'slogdet',
 'slopes',
 'solve',
 'sometrue',
 'sort',
 'sort_complex',
 'source',
 'spacing',
 'specgram',
 'spectral',
 'split',
 'spring',
 'spy',
 'sqrt',
 'square',
 'squeeze',
 'stack',
 'stackplot',
 'standard_cauchy',
 'standard_exponential',
 'standard_gamma',
 'standard_normal',
 'standard_t',
 'std',
 'stem',
 'step',
 'stineman_interp',
 'str0',
 'str_',
 'streamplot',
 'string_',
 'strpdate2num',
 'style',
 'subplot',
 'subplot2grid',
 'subplot_tool',
 'subplots',
 'subplots_adjust',
 'subtract',
 'sum',
 'summer',
 'suptitle',
 'svd',
 'swapaxes',
 'switch_backend',
 'sys',
 'table',
 'take',
 'tan',
 'tanh',
 'tensordot',
 'tensorinv',
 'tensorsolve',
 'test',
 'text',
 'thetagrids',
 'tick_params',
 'ticklabel_format',
 'tight_layout',
 'tile',
 'timedelta64',
 'title',
 'trace',
 'tracemalloc_domain',
 'transpose',
 'trapz',
 'tri',
 'triangular',
 'tricontour',
 'tricontourf',
 'tril',
 'tril_indices',
 'tril_indices_from',
 'trim_zeros',
 'tripcolor',
 'triplot',
 'triu',
 'triu_indices',
 'triu_indices_from',
 'true_divide',
 'trunc',
 'twinx',
 'twiny',
 'typeDict',
 'typeNA',
 'typecodes',
 'typename',
 'types',
 'ubyte',
 'ufunc',
 'uint',
 'uint0',
 'uint16',
 'uint32',
 'uint64',
 'uint8',
 'uintc',
 'uintp',
 'ulonglong',
 'unicode',
 'unicode_',
 'unicode_literals',
 'uniform',
 'uninstall_repl_displayhook',
 'union1d',
 'unique',
 'unpackbits',
 'unravel_index',
 'unsignedinteger',
 'unwrap',
 'ushort',
 'vander',
 'var',
 'vdot',
 'vector_lengths',
 'vectorize',
 'violinplot',
 'viridis',
 'vlines',
 'void',
 'void0',
 'vonmises',
 'vsplit',
 'vstack',
 'waitforbuttonpress',
 'wald',
 'warnings',
 'weibull',
 'where',
 'who',
 'window_hanning',
 'window_none',
 'winter',
 'xcorr',
 'xkcd',
 'xlabel',
 'xlim',
 'xscale',
 'xticks',
 'ylabel',
 'ylim',
 'yscale',
 'yticks',
 'zeros',
 'zeros_like',
 'zipf']

In [9]:
# 라인플롯
plt.plot([1,4,5,10])


Out[9]:
[<matplotlib.lines.Line2D at 0x10fcd6a20>]

In [10]:
plt.plot([1, 4, 9, 16], c="b", lw=5, ls="--", marker="o", ms=15, mec="g", mew=5, mfc="r")
plt.xlim(-0.2, 3.2)
plt.ylim(-1, 18)
plt.show()



In [13]:
# 여러개의 그래프 표현
t = np.arange(0., 5., 0.2)
plt.plot(t, t, 'r--', t, 0.5*t**2, 'bs:', t, 0.2*t**3, 'g^-')
plt.show()



In [16]:
# matplotlib 1.5까진 hold(True)옵션을 줬어야했으나, matplotlib 2.0부터는 모든 플롯 명령에 hold(True)가 자동 적용
plt.plot([1, 4, 9, 16], c="b", lw=5, ls="--", marker="o", ms=15, mec="g", mew=5, mfc="r")
# plt.hold(True)   # <- 1,5 버전에서는 이 코드가 필요하다.
plt.plot([9, 16, 4, 1], c="k", lw=3, ls=":", marker="s", ms=10, mec="m", mew=5, mfc="c")
# plt.hold(False)  # <- 1,5 버전에서는 이 코드가 필요하다.
plt.show()


범례는 legend를 사용


In [17]:
X = np.linspace(-np.pi, np.pi, 256)
C, S = np.cos(X), np.sin(X)
plt.plot(X, C, label="cosine")
plt.plot(X, S, label="sine")
plt.legend(loc=2)
plt.show()


부가 설명은 plt.annotate를 사용


In [19]:
Signature: plt.annotate(*args, **kwargs)
Docstring:
Annotate the point ``xy`` with text ``s``.

Additional kwargs are passed to `~matplotlib.text.Text`.

Parameters
----------

s : str
    The text of the annotation

xy : iterable
    Length 2 sequence specifying the *(x,y)* point to annotate

xytext : iterable, optional
    Length 2 sequence specifying the *(x,y)* to place the text
    at.  If None, defaults to ``xy``.

xycoords : str, Artist, Transform, callable or tuple, optional

    The coordinate system that ``xy`` is given in.

    For a `str` the allowed values are:

    =================   ===============================================
    Property            Description
    =================   ===============================================
    'figure points'     points from the lower left of the figure
    'figure pixels'     pixels from the lower left of the figure
    'figure fraction'   fraction of figure from lower left
    'axes points'       points from lower left corner of axes
    'axes pixels'       pixels from lower left corner of axes
    'axes fraction'     fraction of axes from lower left
    'data'              use the coordinate system of the object being
                        annotated (default)
    'polar'             *(theta,r)* if not native 'data' coordinates
    =================   ===============================================

    If a `~matplotlib.artist.Artist` object is passed in the units are
    fraction if it's bounding box.

    If a `~matplotlib.transforms.Transform` object is passed
    in use that to transform ``xy`` to screen coordinates

    If a callable it must take a
    `~matplotlib.backend_bases.RendererBase` object as input
    and return a `~matplotlib.transforms.Transform` or
    `~matplotlib.transforms.Bbox` object

    If a `tuple` must be length 2 tuple of str, `Artist`,
    `Transform` or callable objects.  The first transform is
    used for the *x* coordinate and the second for *y*.

    See :ref:`plotting-guide-annotation` for more details.

    Defaults to ``'data'``

textcoords : str, `Artist`, `Transform`, callable or tuple, optional
    The coordinate system that ``xytext`` is given, which
    may be different than the coordinate system used for
    ``xy``.

    All ``xycoords`` values are valid as well as the following
    strings:

    =================   =========================================
    Property            Description
    =================   =========================================
    'offset points'     offset (in points) from the *xy* value
    'offset pixels'     offset (in pixels) from the *xy* value
    =================   =========================================

    defaults to the input of ``xycoords``

arrowprops : dict, optional
    If not None, properties used to draw a
    `~matplotlib.patches.FancyArrowPatch` arrow between ``xy`` and
    ``xytext``.

    If `arrowprops` does not contain the key ``'arrowstyle'`` the
    allowed keys are:

    ==========   ======================================================
    Key          Description
    ==========   ======================================================
    width        the width of the arrow in points
    headwidth    the width of the base of the arrow head in points
    headlength   the length of the arrow head in points
    shrink       fraction of total length to 'shrink' from both ends
    ?            any key to :class:`matplotlib.patches.FancyArrowPatch`
    ==========   ======================================================

    If the `arrowprops` contains the key ``'arrowstyle'`` the
    above keys are forbidden.  The allowed values of
    ``'arrowstyle'`` are:

    ============   =============================================
    Name           Attrs
    ============   =============================================
    ``'-'``        None
    ``'->'``       head_length=0.4,head_width=0.2
    ``'-['``       widthB=1.0,lengthB=0.2,angleB=None
    ``'|-|'``      widthA=1.0,widthB=1.0
    ``'-|>'``      head_length=0.4,head_width=0.2
    ``'<-'``       head_length=0.4,head_width=0.2
    ``'<->'``      head_length=0.4,head_width=0.2
    ``'<|-'``      head_length=0.4,head_width=0.2
    ``'<|-|>'``    head_length=0.4,head_width=0.2
    ``'fancy'``    head_length=0.4,head_width=0.4,tail_width=0.4
    ``'simple'``   head_length=0.5,head_width=0.5,tail_width=0.2
    ``'wedge'``    tail_width=0.3,shrink_factor=0.5
    ============   =============================================

    Valid keys for `~matplotlib.patches.FancyArrowPatch` are:

    ===============  ==================================================
    Key              Description
    ===============  ==================================================
    arrowstyle       the arrow style
    connectionstyle  the connection style
    relpos           default is (0.5, 0.5)
    patchA           default is bounding box of the text
    patchB           default is None
    shrinkA          default is 2 points
    shrinkB          default is 2 points
    mutation_scale   default is text size (in points)
    mutation_aspect  default is 1.
    ?                any key for :class:`matplotlib.patches.PathPatch`
    ===============  ==================================================

    Defaults to None

annotation_clip : bool, optional
    Controls the visibility of the annotation when it goes
    outside the axes area.

    If `True`, the annotation will only be drawn when the
    ``xy`` is inside the axes. If `False`, the annotation will
    always be drawn regardless of its position.

    The default is `None`, which behave as `True` only if
    *xycoords* is "data".

Returns
-------
Annotation

In [18]:
plt.plot(X, S, label="sine")
plt.scatter([0], [0], color="r", linewidth=10)
plt.annotate(r'$(0,0)$', xy=(0, 0), xycoords='data', xytext=(-50, 50), 
             textcoords='offset points', fontsize=16, 
             arrowprops=dict(arrowstyle="->", linewidth=3, color="g"))
plt.show()


Figure의 이해

figure : 도화지라고 생각하면 편함

plt.figure(figsize=(10,2)) 또는 plt.gcf()을 사용해 생성


In [22]:
plt.figure(figsize=(10,5))
plt.plot(np.random.randn(100))
plt.show()



In [26]:
# gcf로 figure를 2개 생성해서 그림
f1=plt.gcf()
plt.plot(np.random.randn(100))
f2=plt.gcf()
plt.plot(np.random.randn(100))


Out[26]:
[<matplotlib.lines.Line2D at 0x10ffd5ef0>]

Axes, Subplot

  • 하나의 윈도우(Figure)에 여러개의 플롯을 배열 형태로 보여야 하는 경우-!
  • subplot 명령으로 명시적으로 Axes 객체를 얻어야 함
  • plt.subplot(a,b,c) : a,b는 행렬의 모양을 뜻하고 c는 axb개중 몇번째인지 나타냄
  • plt.subplot(211) 같이 줄여서 작성 가능

In [27]:
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)

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

ax2 = plt.subplot(2, 1, 2)
plt.plot(x2, y2, 'r.-')
plt.xlabel('time (s)')
plt.ylabel('Undamped')
print(ax2)

plt.show()


Axes(0.125,0.536818;0.775x0.343182)
Axes(0.125,0.125;0.775x0.343182)

pandas와 연계


In [3]:
dates = pd.date_range('20160620', periods=6)
df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))

In [4]:
df


Out[4]:
A B C D
2016-06-20 1.824682 -0.848434 1.970067 -0.480283
2016-06-21 -0.974684 0.278418 0.056230 -0.115447
2016-06-22 -0.204583 1.287174 0.379381 -0.379544
2016-06-23 -0.298914 2.237662 0.142003 -0.512020
2016-06-24 -0.858097 -1.022740 -0.334789 -2.065071
2016-06-25 -1.358657 1.703369 -1.373283 -1.228587

In [ ]:
fig, axes = plt.subplots(nrows=2, ncols=2)

df1.plot(ax=axes[0,0])
df2.plot(ax=axes[0,1])

In [5]:
# subplot을 True로 주고 layout 설정-! (이 경우 column name이 기준이 됩니다 )
df.plot(subplots=True, layout=(2,2), figsize=[10,5])
plt.show()


subplot을 False로 주는 경우


In [7]:
df.plot(subplots=False, figsize=[10,5])
plt.show()


ticks 설정

  • plt.xticks(fontsize=14, rotation=90)
  • matplotlib.text.Text 클래스에 있는 것들은 모두 사용가능

locs, labels = xticks()

plot y축 reverse

  • plt.gca().invert_yaxis()

글자크기 조절

  • mpl.rcParams['font.size'] = 20
  • mpl.rcParams['xtick.labelsize'] = 20
  • plt.title('platform', fontsize=25)

layout 조절

  • plt.tight_layout()

colobar

  • cb = plt.colorbar()

y축 쉼표 추가하는 방법

  • ax.yaxis.set_major_formatter(
      tkr.FuncFormatter(lambda y,  p: format(int(y), ',')))

In [9]:
data = pd.DataFrame(np.random.randint(1500, size=(100, 2)), columns=['meas', 'modeled'])
# data = pd.read_csv('data.csv')

x = data['meas']
y = data['modeled']

xmin = 0
xmax = 1500
ymin = 0
ymax = 1500

fig, ax = plt.subplots()
plt.hexbin(x, y, cmap=plt.cm.gnuplot2_r)
plt.axis([xmin, xmax, ymin, ymax])
plt.xlabel("Measured baseflow, in cfs")
plt.ylabel("Simulated baseflow, in cfs")
cb = plt.colorbar()
cb.set_label('count')
p2, = plt.plot([0,1500],[0,1500], c='g')
l2 = plt.legend([p2], ["1:1 Line"], loc=2)

ax.yaxis.set_major_formatter(
        tkr.FuncFormatter(lambda y,  p: format(int(y), ',')))

plt.show()



In [ ]: