[Matplotlib] 07. Plot Main: Plot()

in #kr-dev6 years ago

07. Plot Main: Plot()

사실 그동안 예제 프로그램에서 계속 써왔던 함수, plot()에 대하여 짚고 넘어가 보도록 하겠습니다 .
Axes.plot(*args, data=None, **kwargs)

플롯 함수는 주어진 x와 y값에 대하여 직선 혹은 마커를 표시해줍니다.
위 웹페이지에 나와 있듯이, 간단한 사용법은 다음과 같습니다.

plot([x], y, [fmt], data=None, **kwargs)

만약 x 값을 생략할 경우 range(len(y))가 할당됩니다.
포맷 fmt는 색깔, 마커의 모양, 그리고 선모양을 간단히 지정할 수 있습니다.

fmt = '[color][marker][line]'

그래서 다음 두 줄은 서로 같은 의미입니다.

plot(x, y, 'go--', linewidth=2, markersize=12)
plot(x, y, color='green', marker='o', linestyle='dashed', linewidth=2, markersize=12)



이제 다양한 색깔과 마커와 선 모양을 조합하여 그림을 그리는 프로그램을 보시겠습니다.
이번 프로그램에는 function()을 따로 정의하여 그림의 공통된 부분이 반복되지 않도록 하였으며, numpy.linspace()와 "%"를 이용한 mod() 기능 (나눗셈의 나머지)도 사용되었음을 알려드립니다.

import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator, MultipleLocator

def plot_accessary(ax,subtit=''):
    ax.set_title(subtit,x=0.05,y=0.9,ha='left',fontsize=13)

    ax.set_xlim(-4,4)
    ax.xaxis.set_major_locator(MultipleLocator(1))   # For Major Ticks
    ax.xaxis.set_minor_locator(MultipleLocator(0.5))   # For minor Ticks
    ax.set_xlabel('X',fontsize=12)

    ax.set_ylim(-1.25,1.75)
    ax.set_ylabel('Y',fontsize=12)
    ax.yaxis.set_minor_locator(AutoMinorLocator(2))

    ax.tick_params(axis='both',which='major',labelsize=10)
    ax.axhline(y=0.,color='k',linestyle=':')
    ax.axvline(x=0.,color='k',ls=':',lw=0.5)

###--- Main ---###
color_names = ['b','g','r','c','m','y','k',]; ncolor=len(color_names)
markers = ['o','v','^','d','s','D','*','+','x',]; nmarker=len(markers)
line_styles = ['-','--','-.',':',]; nlines=len(line_styles)
npts=3   # Initial number of data points
abc='abc'

###--- Plotting Start ---###
##-- Page Setup --##
fig = plt.figure()            # Define "figure" instance
fig.set_size_inches(6,4.5)    # Physical page size in inches, (lx,ly)
suptit="Axes.plot()"
fig.suptitle(suptit,fontsize=15)   # Title for the page

for i in range(12):
    ###--- Synthesizing data to be plotted ---###
    npts+=i
    x = np.linspace(-4,4,npts)    
    ysin = np.sin(x)

    line_properties=[color_names[i%ncolor]+markers[i%nmarker],
                     color_names[i%ncolor]+markers[i%nmarker]+line_styles[i%nlines],
                     color_names[i%ncolor]+line_styles[i%nlines]]

    for j in range(3):
        ##-- Plotting for axis1: Marker only --##
        ax1 = fig.add_subplot(1,1,1)   # subplot(# of rows, # of columns, indicater)
        lp=line_properties[j]
        line1=ax1.plot(x,ysin,lp,markersize=7,linewidth=2.,label='y=sin(x)')     # plotting line graph
        subtit="({}{}) plot '{}' with {} points".format(i+1,abc[j],lp,npts)
        plot_accessary(ax1,subtit)
        ax1.legend(loc=1,fontsize=12)
        ##-- Saving Pic --##
        outfnm = "./07_plot_main.plot.{}{}.png".format(i,abc[j])     # File format is decided by the file name, eg. png here
        fig.savefig(outfnm,dpi=100,facecolor='0.9')   # dpi: pixels per inch
        plt.cla()

sys.exit()

위 프로그램을 실행시키면 다음과 같은, 36장의 그림이 나옵니다.

07_plot_main.plot.gif

위의 색깔의 경우, 파이쏜에서 미리 정의된 색깔 약어 (알파벳 1글자)는 모두 8개 입니다. (위에 7개 + 'w' for white) 그 외에도 HTML에서 사용되는 색들도 대부분 사용 가능 합니다.
예를 들면

color='salmon'
color='#FA8072'
color=(250/255.,128/255.,114/255.)

모두 같은 색깔로 표시됩니다.
색에 대한 더 자세한 내용은 다음 imshow() 함수를 설명하며 덧붙이겠습니다.

이상 plot()에 대해 알아보았습니다.


"""
제 개인적 목표는

  1. Object-Oriented Programming과 친해지기
  2. Github와 친해지기 입니다.

이 목표에 닿기 위해 일단 제가 나름 좀 아는 Python, 그 중에서도 NumpyMatplotlib로부터 시작하려 합니다.
"""

List

[Matplotlib] 00. Intro + 01. Page Setup
[Matplotlib] 02. Axes Setup: Subplots
[Matplotlib] 03. Axes Setup: Text, Label, and Annotation
[Matplotlib] 04. Axes Setup: Ticks and Tick Labels
[Matplotlib] 05. Plot Accessories: Grid and Supporting Lines
[Matplotlib] 06. Plot Accessories: Legend
[Matplotlib] 07. Plot Main: Plot

Sort:  

therising: 2 SBD (2.5배 기준 $5 기대)
99.91%에 글 포스팅, 8분만에 보팅.
전체 대기 물량은 30.25 SBD.
스팀가격 $1.85, 스파 488,014, 100% 보팅시 $60.95일 때,
보팅 6.5% 받아서 $3.96 받음.

총평:
https://steembottracker.com/#bid에 예상 보팅 가격이 정확하지 않음. steemnow.com 계산기로 계산했을 때 $60.95인데, 위 트래커에는 $102.34로 나옴. 당연히 $102.34 기준으로는 이익이 되는 금액도 $60.95로 생각하면 손해일 수 있음.
2 SBD 전송시 20SBD였으나 이후 막판 러쉬로 30SBD로 증가. 따라서 예상보다 적은 금액이 보팅됨. 하지만 30분 안에 보팅받아 손해는 아닐 수 있음. 1주일 후 스팀 가격 $2 회복 희망.

Coin Marketplace

STEEM 0.30
TRX 0.12
JST 0.033
BTC 64230.75
ETH 3149.35
USDT 1.00
SBD 3.85