import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
산점도 응용예제4 (무상관과 독립)
예시자료
-
예시1
= np.random.uniform(low=0, high=1, size=10000) # 0~1사이의 10000개
x1 = np.random.uniform(low=0, high=1, size=10000) y1
',')
plt.plot(x1,y1,0], y1[0],'or') plt.plot(x1[
-
예시2 (원)
= x1**2 + y1**2 # 반지름
_r2 _r2
array([0.32841936, 0.65211343, 0.8620744 , ..., 0.99310561, 0.35628571,
0.32995271])
len(_r2)
10000
=x1[_r2<1]
x2=y1[_r2<1] y2
',') plt.plot(x2,y2,
-
예시3 (이변량정규분포)
= np.random.randn(10000)
x3 = np.random.randn(10000) y3
',') plt.plot(x3,y3,
상관계수
예시1, 예시2, 예시3의 산점도를 보고 상관계수가 얼마인지 예상해보라. 실제 계산결과와 확인하라.
np.corrcoef([x1,y1])
array([[1. , 0.01268214],
[0.01268214, 1. ]])
np.corrcoef([x2,y2])
array([[ 1. , -0.28666195],
[-0.28666195, 1. ]])
np.corrcoef([x3,y3])
array([[1. , 0.00827362],
[0.00827362, 1. ]])
독립을 따져보자.
= plt.subplots(1,2,figsize=(8,4))
fig, ax 0].plot(x1,y1,',')
ax[1].plot(x2,y2,',') ax[
def g(intval, data, ax, col = 'r'):
= intval
a,b = data
x,y = (a<x) & (x<b)
idx ',',color=col) ax.plot(x[idx], y[idx],
fig
-0.1,0.1],[x1,y1],ax[0])
g([-0.1,0.1],[x2,y2],ax[1])
g([ fig
0.79,0.99],[x1,y1],ax[0],col='m')
g([0.79,0.99],[x2,y2],ax[1],col='m')
g([ fig
-
예시3
',') plt.plot(x3,y3,
= plt.subplots()
fig, ax ',',color='gray') # g함수 사용하기 위해 이렇게 해보자 ax.plot(x3,y3,
-2.5,-1.5],[x3,y3],ax,col='r')
g([ fig
-2.5,-1.5],[x3,y3],ax,col='r')
g([-0.5,+0.5],[x3,y3],ax,col='b')
g([+1.5,+2.5],[x3,y3],ax,col='g')
g([ fig
= (-0.5<x3) & (x3<0.5)
idx # 위의 파란색을 뽑아보자 plt.hist(y3[idx])
(array([ 5., 32., 188., 512., 938., 1054., 722., 303., 79.,
16.]),
array([-3.81904376, -3.09056613, -2.36208849, -1.63361085, -0.90513321,
-0.17665557, 0.55182207, 1.28029971, 2.00877735, 2.73725499,
3.46573263]),
<BarContainer object of 10 artists>)
= (-0.5<x3) & (x3<0.5)
idx ; # 맨 뒤 세미콜론 붙이면 위의 글씨 안나옴 plt.hist(y3[idx])
def h(intval, data, ax, col):
= intval
a,b = data
x,y = (a<x) & (x<b)
idx =col) ax.hist(y[idx], color
= plt.subplots(5,2,figsize=(8,16))
fig,ax 0,0].plot(x3,y3,',',color='gray'); g([-2.5,-1.5],[x3,y3],ax[0,0],col='r')
ax[1,0].plot(x3,y3,',',color='gray'); g([-1.5,-0.5],[x3,y3],ax[1,0],col='g')
ax[2,0].plot(x3,y3,',',color='gray'); g([-0.5,+0.5],[x3,y3],ax[2,0],col='b')
ax[3,0].plot(x3,y3,',',color='gray'); g([+0.5,+1.5],[x3,y3],ax[3,0],col='m')
ax[4,0].plot(x3,y3,',',color='gray'); g([+1.5,+2.5],[x3,y3],ax[4,0],col='lime')
ax[
-2.5,-1.5],[x3,y3],ax[0,1],col='r')
h([-1.5,-0.5],[x3,y3],ax[1,1],col='g')
h([-0.5,+0.5],[x3,y3],ax[2,1],col='b')
h([+0.5,+1.5],[x3,y3],ax[3,1],col='m')
h([+1.5,+2.5],[x3,y3],ax[4,1],col='lime') h([
mpl에 대한 미세먼지 팁(1)
!git add .
!git commit -m .
!git push
[main d563e82] .
15 files changed, 63188 insertions(+)
create mode 100644 posts/Data Visualization/.ipynb_checkpoints/DV_1(0910)-checkpoint.ipynb
create mode 100644 posts/Data Visualization/.ipynb_checkpoints/DV_2(0914)-checkpoint.ipynb
create mode 100644 posts/Data Visualization/.ipynb_checkpoints/DV_3(0919)-checkpoint.ipynb
create mode 100644 posts/Data Visualization/.ipynb_checkpoints/DV_3(0921)-checkpoint.ipynb
create mode 100644 posts/Data Visualization/.ipynb_checkpoints/DV_4(0926)-checkpoint.ipynb
create mode 100644 posts/Data Visualization/DV_1(0910).ipynb
create mode 100644 posts/Data Visualization/DV_2(0914).ipynb
create mode 100644 posts/Data Visualization/DV_3(0919).ipynb
create mode 100644 posts/Data Visualization/DV_3(0921).ipynb
create mode 100644 posts/Data Visualization/DV_4(0926).ipynb
create mode 100644 posts/Data Visualization/Unequalized_Hawkes_Bay_NZ.jpg
create mode 100644 posts/Data Visualization/Unequalized_Hawkes_Bay_NZ.jpg.1
create mode 100644 posts/Data Visualization/hw_img.png
create mode 100644 posts/Data Visualization/hw_img.png.1
create mode 100644 posts/Data Visualization/hw_img.png.2
Enumerating objects: 16, done.
Counting objects: 100% (16/16), done.
Delta compression using up to 16 threads
Compressing objects: 100% (14/14), done.
Writing objects: 100% (14/14), 1.90 MiB | 3.52 MiB/s, done.
Total 14 (delta 4), reused 0 (delta 0)
remote: Resolving deltas: 100% (4/4), completed with 2 local objects.
To https://github.com/boram-coco/coco.git
f1df7bb..d563e82 main -> main
그림만 보고 싶을때
0,1,2,3],[2,3,4,1]) plt.plot([
2,3,4,1]) # [0,1,2,3] 이 기본 default 값이므로 생략 가능 plt.plot([
2,3,4,1]); # 그림 위에 올라가는거 없어짐 plt.plot([
marker size, line width
2,3,4,1],'o',markersize=13) # markersize = ms 라고 써도 됨 plt.plot([
2,3,4,1],'--',lw=12) plt.plot([
label, legend
2,3,4,1],'--o', label='A')
plt.plot([4,3.2,1,3],'--o', label='B')
plt.plot([# 범례.. 위의 label plt.legend()
<matplotlib.legend.Legend at 0x7fbc8767d050>
색깔조정 (C0, C1,…)
2,3,4,1],'--o', label='A', color='C1')
plt.plot([4,3.2,1,3],'--o', label='B', color='C0') # 그래프 위아래의 선 색 변경시 color='C0'
plt.plot([ plt.legend()
<matplotlib.legend.Legend at 0x7fbc86d99750>
title
-
방법1
1,2,3,2])
plt.plot(['title') plt.title(
Text(0.5, 1.0, 'title')
-
방법2
= plt.subplots()
fig, ax 'asdf') ax.set_title(
Text(0.5, 1.0, 'asdf')
suptitle
= plt.subplots(2,2)
fig, ax 0,0].plot([1,2,3,2],'--o',label='A',color='C0')
ax[0,0].set_title('(a)')
ax[0,1].plot([3,2.1,1,3],'--o',label='B',color='C1')
ax[0,1].set_title('(b)')
ax[1,0].plot([-3,-2.1,-1,-3],'--o',label='B',color='C2')
ax[1,0].set_title('(c)')
ax[1,1].plot([3,-2.1,1,-3],'--o',label='B',color='C3')
ax[1,1].set_title('(d)')
ax[#plt.suptitle('suptitle') 둘다된다
'suptitle') fig.suptitle(
Text(0.5, 0.98, 'suptitle')
tight_layout()
= plt.subplots(2,2)
fig, ax 0,0].plot([1,2,3,2],'--o',label='A',color='C0')
ax[0,0].set_title('(a)')
ax[0,1].plot([3,2.1,1,3],'--o',label='B',color='C1')
ax[0,1].set_title('(b)')
ax[1,0].plot([-3,-2.1,-1,-3],'--o',label='B',color='C2')
ax[1,0].set_title('(c)')
ax[1,1].plot([3,-2.1,1,-3],'--o',label='B',color='C3')
ax[1,1].set_title('(d)')
ax['suptitle')
fig.suptitle(# 컴퓨터에서 알아서 이쁘게 레이아웃 설정 fig.tight_layout()
fig, ax, plt 소속
예시
= plt.subplots()
fig, ax 1,2,3,1]) ax.plot([
-
fig에는 있고 ax에는 없는 것
add_axes, tight_layout, suptitle, …
set(dir(fig)) - set(dir(ax)) # fig에만 있는 함수
{'_add_axes_internal',
'_align_label_groups',
'_axobservers',
'_axstack',
'_button_pick_id',
'_cachedRenderer',
'_canvas_callbacks',
'_constrained',
'_constrained_layout_pads',
'_dpi',
'_get_dpi',
'_get_draw_artists',
'_gridspecs',
'_localaxes',
'_normalize_grid_string',
'_original_dpi',
'_process_projection_requirements',
'_repr_html_',
'_scroll_pick_id',
'_set_dpi',
'_suplabels',
'_suptitle',
'_supxlabel',
'_supylabel',
'_tight_parameters',
'add_axes',
'add_axobserver',
'add_gridspec',
'add_subfigure',
'add_subplot',
'align_labels',
'align_xlabels',
'align_ylabels',
'autofmt_xdate',
'bbox_inches',
'canvas',
'clf',
'colorbar',
'delaxes',
'dpi',
'dpi_scale_trans',
'draw_without_rendering',
'execute_constrained_layout',
'figbbox',
'figimage',
'frameon',
'gca',
'get_axes',
'get_constrained_layout',
'get_constrained_layout_pads',
'get_dpi',
'get_edgecolor',
'get_figheight',
'get_figwidth',
'get_frameon',
'get_linewidth',
'get_size_inches',
'get_tight_layout',
'ginput',
'legends',
'number',
'savefig',
'sca',
'set_canvas',
'set_constrained_layout',
'set_constrained_layout_pads',
'set_dpi',
'set_edgecolor',
'set_figheight',
'set_figwidth',
'set_frameon',
'set_linewidth',
'set_size_inches',
'set_tight_layout',
'show',
'subfigs',
'subfigures',
'subplot_mosaic',
'subplotpars',
'subplots',
'subplots_adjust',
'suppressComposite',
'suptitle',
'supxlabel',
'supylabel',
'tight_layout',
'transFigure',
'transSubfigure',
'waitforbuttonpress'}
-
ax에는 있고 fig에는 없는 것
boxplot, hist, plot, set_title, …
set(dir(ax)) - set(dir(fig)) # ax만 있는 함수
{'ArtistList',
'_add_text',
'_adjustable',
'_alias_map',
'_anchor',
'_aspect',
'_autoscaleXon',
'_autoscaleYon',
'_autotitlepos',
'_axes',
'_axes_class',
'_axes_locator',
'_axis_names',
'_axisbelow',
'_box_aspect',
'_check_no_units',
'_children',
'_colorbars',
'_convert_dx',
'_current_image',
'_deprecate_noninstance',
'_facecolor',
'_fill_between_x_or_y',
'_frameon',
'_gen_axes_patch',
'_gen_axes_spines',
'_get_axis_list',
'_get_axis_map',
'_get_lines',
'_get_pan_points',
'_get_patches_for_fill',
'_get_view',
'_gridOn',
'_init_axis',
'_label_outer_xaxis',
'_label_outer_yaxis',
'_left_title',
'_make_twin_axes',
'_mouseover_set',
'_navigate',
'_navigate_mode',
'_originalPosition',
'_parse_scatter_color_args',
'_pcolor_grid_deprecation_helper',
'_pcolorargs',
'_position',
'_prepare_view_from_bbox',
'_process_unit_info',
'_projection_init',
'_quiver_units',
'_rasterization_zorder',
'_remove_legend',
'_request_autoscale_view',
'_right_title',
'_sci',
'_set_lim_and_transforms',
'_set_position',
'_set_title_offset_trans',
'_set_view',
'_set_view_from_bbox',
'_shared_axes',
'_sharex',
'_sharey',
'_stale_viewlims',
'_subplotspec',
'_twinned_axes',
'_unit_change_handler',
'_unstale_viewLim',
'_update_image_limits',
'_update_line_limits',
'_update_patch_limits',
'_update_title_position',
'_update_transScale',
'_use_sticky_edges',
'_validate_converted_limits',
'_viewLim',
'_xaxis_transform',
'_xmargin',
'_yaxis_transform',
'_ymargin',
'acorr',
'add_child_axes',
'add_collection',
'add_container',
'add_image',
'add_line',
'add_patch',
'add_table',
'angle_spectrum',
'annotate',
'apply_aspect',
'arrow',
'autoscale',
'autoscale_view',
'axhline',
'axhspan',
'axis',
'axison',
'axline',
'axvline',
'axvspan',
'bar',
'bar_label',
'barbs',
'barh',
'boxplot',
'broken_barh',
'bxp',
'can_pan',
'can_zoom',
'change_geometry',
'child_axes',
'cla',
'clabel',
'cohere',
'collections',
'containers',
'contains_point',
'contour',
'contourf',
'csd',
'dataLim',
'drag_pan',
'end_pan',
'errorbar',
'eventplot',
'figbox',
'fill',
'fill_between',
'fill_betweenx',
'fmt_xdata',
'fmt_ydata',
'format_coord',
'format_xdata',
'format_ydata',
'get_adjustable',
'get_anchor',
'get_aspect',
'get_autoscale_on',
'get_autoscalex_on',
'get_autoscaley_on',
'get_axes_locator',
'get_axisbelow',
'get_box_aspect',
'get_data_ratio',
'get_fc',
'get_frame_on',
'get_geometry',
'get_gridspec',
'get_images',
'get_legend',
'get_legend_handles_labels',
'get_lines',
'get_navigate',
'get_navigate_mode',
'get_position',
'get_rasterization_zorder',
'get_renderer_cache',
'get_shared_x_axes',
'get_shared_y_axes',
'get_subplotspec',
'get_title',
'get_xaxis',
'get_xaxis_text1_transform',
'get_xaxis_text2_transform',
'get_xaxis_transform',
'get_xbound',
'get_xgridlines',
'get_xlabel',
'get_xlim',
'get_xmajorticklabels',
'get_xminorticklabels',
'get_xscale',
'get_xticklabels',
'get_xticklines',
'get_xticks',
'get_yaxis',
'get_yaxis_text1_transform',
'get_yaxis_text2_transform',
'get_yaxis_transform',
'get_ybound',
'get_ygridlines',
'get_ylabel',
'get_ylim',
'get_ymajorticklabels',
'get_yminorticklabels',
'get_yscale',
'get_yticklabels',
'get_yticklines',
'get_yticks',
'grid',
'has_data',
'hexbin',
'hist',
'hist2d',
'hlines',
'ignore_existing_data_limits',
'imshow',
'in_axes',
'indicate_inset',
'indicate_inset_zoom',
'inset_axes',
'invert_xaxis',
'invert_yaxis',
'is_first_col',
'is_first_row',
'is_last_col',
'is_last_row',
'label_outer',
'legend_',
'locator_params',
'loglog',
'magnitude_spectrum',
'margins',
'matshow',
'minorticks_off',
'minorticks_on',
'name',
'numCols',
'numRows',
'pcolor',
'pcolorfast',
'pcolormesh',
'phase_spectrum',
'pie',
'plot',
'plot_date',
'psd',
'quiver',
'quiverkey',
'redraw_in_frame',
'relim',
'reset_position',
'scatter',
'secondary_xaxis',
'secondary_yaxis',
'semilogx',
'semilogy',
'set_adjustable',
'set_anchor',
'set_aspect',
'set_autoscale_on',
'set_autoscalex_on',
'set_autoscaley_on',
'set_axes_locator',
'set_axis_off',
'set_axis_on',
'set_axisbelow',
'set_box_aspect',
'set_fc',
'set_frame_on',
'set_navigate',
'set_navigate_mode',
'set_position',
'set_prop_cycle',
'set_rasterization_zorder',
'set_subplotspec',
'set_title',
'set_xbound',
'set_xlabel',
'set_xlim',
'set_xmargin',
'set_xscale',
'set_xticklabels',
'set_xticks',
'set_ybound',
'set_ylabel',
'set_ylim',
'set_ymargin',
'set_yscale',
'set_yticklabels',
'set_yticks',
'sharex',
'sharey',
'specgram',
'spines',
'spy',
'stackplot',
'stairs',
'start_pan',
'stem',
'step',
'streamplot',
'table',
'tables',
'tick_params',
'ticklabel_format',
'title',
'titleOffsetTrans',
'transAxes',
'transData',
'transLimits',
'transScale',
'tricontour',
'tricontourf',
'tripcolor',
'triplot',
'twinx',
'twiny',
'update_datalim',
'update_params',
'use_sticky_edges',
'viewLim',
'violin',
'violinplot',
'vlines',
'xaxis',
'xaxis_date',
'xaxis_inverted',
'xcorr',
'yaxis',
'yaxis_date',
'yaxis_inverted'}
set(dir(ax)) & set(dir(fig)) # 교집합
{'_PROPERTIES_EXCLUDED_FROM_SET',
'__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getstate__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__setstate__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'_agg_filter',
'_alpha',
'_animated',
'_callbacks',
'_clipon',
'_clippath',
'_cm_set',
'_default_contains',
'_gci',
'_get_clipping_extent_bbox',
'_gid',
'_in_layout',
'_label',
'_mouseover',
'_path_effects',
'_picker',
'_rasterized',
'_remove_method',
'_set_alpha_for_array',
'_set_artist_props',
'_set_gc_clip',
'_sketch',
'_snap',
'_stale',
'_sticky_edges',
'_tight',
'_transform',
'_transformSet',
'_update_set_signature_and_docstring',
'_url',
'_visible',
'add_artist',
'add_callback',
'artists',
'axes',
'bbox',
'callbacks',
'clear',
'clipbox',
'contains',
'convert_xunits',
'convert_yunits',
'draw',
'draw_artist',
'figure',
'findobj',
'format_cursor_data',
'get_agg_filter',
'get_alpha',
'get_animated',
'get_children',
'get_clip_box',
'get_clip_on',
'get_clip_path',
'get_cursor_data',
'get_default_bbox_extra_artists',
'get_facecolor',
'get_figure',
'get_gid',
'get_in_layout',
'get_label',
'get_path_effects',
'get_picker',
'get_rasterized',
'get_sketch_params',
'get_snap',
'get_tightbbox',
'get_transform',
'get_transformed_clip_path_and_affine',
'get_url',
'get_visible',
'get_window_extent',
'get_zorder',
'have_units',
'images',
'is_transform_set',
'legend',
'lines',
'mouseover',
'patch',
'patches',
'pchanged',
'pick',
'pickable',
'properties',
'remove',
'remove_callback',
'set',
'set_agg_filter',
'set_alpha',
'set_animated',
'set_clip_box',
'set_clip_on',
'set_clip_path',
'set_facecolor',
'set_figure',
'set_gid',
'set_in_layout',
'set_label',
'set_path_effects',
'set_picker',
'set_rasterized',
'set_sketch_params',
'set_snap',
'set_transform',
'set_url',
'set_visible',
'set_zorder',
'stale',
'stale_callback',
'sticky_edges',
'text',
'texts',
'update',
'update_from',
'zorder'}
-
plt는 대부분 다 있음. (의미상 명확한건 대충 알아서 fig, ax에 접근해서 처리해준다)
- plt.tight_layout, plt.suptitle, plt.boxplot, plt.hist, plot.plot
- plt.set_title 은 없지만 plt.title 은 있음
- plt.add_axes 는 없음..
set(dir(plt)) & {'add_axes'}
set()
x축, y축 label 설정
= plt.subplots()
fig,ax 1,2,3,2])
ax.plot([#ax.set_xlabel('x',size=36, style='italic')
= {'size':36, 'family':'serif', 'style':'italic'} #family:글꼴
_dct 'x',_dct) #옵션을 딕셔너리 형태로 해서 이렇게 표현도 가능 ax.set_xlabel(
Text(0.5, 0, 'x')
'xlabel',size=16,family='serif',weight=1000,style='italic')
ax.xaxis.set_label_text(#_fontsettings={'size':16,'family':'serif','weight'=1000,'style':'italic'}
#ax.xaxis.set_label_text('xlabel',_fontsettings)
fig
# weight 굵음
# xaxis 도 가능.. (x축)
폰트ref : https://matplotlib.org/stable/api/font_manager_api.html#matplotlib.font_manager.FontProperties
size:
fontweight: 0~1000
family: ‘serif’, ‘sans-serif’, ‘monospace’
style: ‘normal’, ‘italic’
ax.set_xlabel??
Signature: ax.set_xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs) Source: def set_xlabel(self, xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs): """ Set the label for the x-axis. Parameters ---------- xlabel : str The label text. labelpad : float, default: :rc:`axes.labelpad` Spacing in points from the Axes bounding box including ticks and tick labels. If None, the previous value is left as is. loc : {'left', 'center', 'right'}, default: :rc:`xaxis.labellocation` The label position. This is a high-level alternative for passing parameters *x* and *horizontalalignment*. Other Parameters ---------------- **kwargs : `.Text` properties `.Text` properties control the appearance of the label. See Also -------- text : Documents the properties supported by `.Text`. """ if labelpad is not None: self.xaxis.labelpad = labelpad protected_kw = ['x', 'horizontalalignment', 'ha'] if {*kwargs} & {*protected_kw}: if loc is not None: raise TypeError(f"Specifying 'loc' is disallowed when any of " f"its corresponding low level keyword " f"arguments ({protected_kw}) are also " f"supplied") else: loc = (loc if loc is not None else mpl.rcParams['xaxis.labellocation']) _api.check_in_list(('left', 'center', 'right'), loc=loc) if loc == 'left': kwargs.update(x=0, horizontalalignment='left') elif loc == 'center': kwargs.update(x=0.5, horizontalalignment='center') elif loc == 'right': kwargs.update(x=1, horizontalalignment='right') return self.xaxis.set_label_text(xlabel, fontdict, **kwargs) File: ~/anaconda3/envs/py37/lib/python3.7/site-packages/matplotlib/axes/_base.py Type: method
숙제
아래와 같이 표준정규분포에서 100개의 난수를 생성하여 \(\boldsymbol{\epsilon}=(\epsilon_1,\epsilon_2,\dots,\epsilon_{100})\) 와 같은 벡터를 만들었다고 하자.
43052)
np.random.seed(= np.random.randn(100) ϵ
아래는 \((t,\epsilon_t)\)를 그린 그림이다. (단 \(t=1,2,\dots,100\))
1,101),ϵ,'--o') plt.plot(np.arange(
(1)
\(\epsilon_t\) 와 \(\epsilon_{t-1}\)은 독립이라고 보여지는가?
(2)
아래의 수식을 만족하는 벡터 \({\boldsymbol y} = (y_1,y_2,\dots, y_{100})\) 을 생성하라. (단 \(y_1=\epsilon_1\))
\[ y_t = y_{t-1} + \epsilon_t\]
(3)
\((t,y_t)\)의 dot-connected plot을 그려라.
(4)
\(y_t\)와 \(y_{t-1}\)은 독립이라고 볼 수 있는가?