Matplotlib으로 바 그래프 그리기

전에 작성한 글에 이어서 이번에는 기본적인 바 그래프를 그려 보겠습니다.

Code

# 필요한 모듈을 임포트
import numpy as np
import matplotlib.pyplot as plt

# number of data in each group
n_groups = 4

# 각 데이터의 평균
means_group1 = (121.32, 272.88, 277.08, 227.03)
means_group2 = (141.21, 472.15, 457.01, 327.34)
# 각 데이터의 표준편차
std_group1 = (8.0, 5.8, 2.0, 19.9)
std_group2 = (5.0, 15.8, 12.0, 9.1)

fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.3 # space between bar

rects2 = plt.bar(index, means_group1, bar_width,
#color='r' , # color of bar
yerr=std_group1, # error bar
capsize=3, # cap length for error bar
ecolor='k', # color of error bar
label='group1')

rects2 = plt.bar(index + bar_width, means_group2, bar_width,
#color='b', # color of bar
yerr=std_group2, # error bar
capsize=3, # cap length for error bar
ecolor='k', # color of error bar
label='treatment group')

plt.xlabel('Sample') # x축 이름
plt.ylabel('mg/ml') # y축 이름
plt.title('TEST') # 그래프 이름
plt.xticks(index + bar_width/2, ('E7', 'E8', 'E9', 'E10')) # x축 틱
plt.legend() # 레전드 표시
plt.show()

두가지 그룹 (group1, group2)에 각각 (E7, E8, E9, E10) 샘플이 있고 여러번 값을 측정하여 표준편차를 에러바로 표시하였습니다.

Result

결과는 아래와 같습니다.
bar_graph

Matplotlib 으로 에러바 선 그래프 그리기

파이썬의 Matplotlib을 이용해 가장 간단하면서도 많이 사용되는 에러바 선 그래프를 그려보겠습니다.

Code:

import matplotlib.pyplot as plt

## color code
# b: blue
# g: green
# r: red
# c: cyan
# m: magenta
# y: yellow
# k: black
# w: white

## marker style
# ================ ===============================
# character description
# ================ ===============================
# - solid line style
# -- dashed line style
# -. dash-dot line style
# : dotted line style
# . point marker
# , pixel marker
# o circle marker
# v triangle_down marker
# ^ triangle_up marker
# < triangle_left marker # > triangle_right marker
# 1 tri_down marker
# 2 tri_up marker
# 3 tri_left marker
# 4 tri_right marker
# s square marker
# p pentagon marker
# * star marker
# h hexagon1 marker
# H hexagon2 marker
# + plus marker
# x x marker
# D diamond marker
# d thin_diamond marker
# | vline marker
# _ hline marker
# ================ ===============================

## Drawing each lines
# plot first line graph
plt.errorbar(
[0.3, 1 ,2 ,3], # X
[1000,400,90,16], # Y
yerr=[54,12,41,4], # Y-errors
fmt="ro-", # format line like for plot()
linewidth=2, # width of plot line
elinewidth=0.5,# width of error bar line
ecolor='k', # color of error bar
capsize=3, # cap length for error bar
capthick=0.5 # cap thickness for error bar
)
# plot second line graph
plt.errorbar(
[0.3, 1 ,2 ,3], # X
[1120,340,49,46], # Y
yerr=[134,124,21,9], # Y-errors
fmt="bo-", # format line like for plot()
linewidth=2, # width of plot line
elinewidth=0.5,# width of error bar line
ecolor='k', # color of error bar
capsize=3, # cap length for error bar
capthick=0.5 # cap thickness for error bar
)
# plot Third line graph
plt.errorbar(
[0.3, 1 ,2 ,3], # X
[619,674,359,126], # Y
yerr=[44,34,21,13], # Y-errors
fmt="ko-", # format line like for plot()
linewidth=2, # width of plot line
elinewidth=0.5,# width of error bar line
ecolor='k', # color of error bar
capsize=3, # cap length for error bar
capthick=0.5 # cap thickness for error bar
)

## Settings
# plt.legend() # show figure legend
plt.ylabel('Concentration(ng/ml)')
plt.xlabel('Hours')
plt.title('Python plot')
plt.yscale('log') #Set y-axis scale
# plt.xlim((0.5,4.5)) #Set X-axis limits
# plt.ylim((0,100)) #Set Y-axis limits
# plt.xticks([1,2,3,4]) #get only ticks we want
# plt.yticks([0,5,10,15,20])

## showing plot
plt.show()

데이터를 추가 하려면 각각의 plt.errorbar()함수를 추가하고, 모양을 변경하려면 fmt 옵션을 변경하면 됩니다.

Y축의 scale은 보통 ‘linear’를 사용하지만 이번에는 ‘log’ scale로 만들었습니다.

Linear로 하면 낮은 값의 오차가 보이지 않기 때문입니다.

Results:

Screenshot from 2017-06-24 08.50.04

References:

scientificpythonsnippets

텍스트 에디터 비교 (ATOM vs. Sublime Text vs. Notepad++)

파이썬 코딩을 하면서 여러가지 IDE를 시도해봤지만, 실행속도가 빠르면서 간편하게 사용할 수 있는 아래 3가지의 텍스트 에디터로 항상 되돌아 오게 된다.

  • ATOM
  • Sublime text
  • Notepad++

더 좋은 에디터가 있는지는 모르겠지만, 일단 내가 아는것은 저것이 전부다. 모두 기능적으로는 매우 충분하므로 맘에 드는걸로 골라 쓰면 된다.

1. ATOM

64E9iYC

github에서 오픈소스로 개발했다는 점에서 끌렸다. 모양도 맘에 들었고 다른 것들보다 사용 설정도 쉽다. 문제는 1.0 버전 기준으로 오류가 간혹나며, 속도가 상대적으로 느리다.

보기에도 좋고 가장 쉽게 쓸수 있는데 속도가 느리다.

2. Sublime Text 3

Sublime-Text-3

텍스트 에디터 종결자, 모양은 ATOM보다 못하지만 Notepad++ 보다는 엄청나게 좋다. 빠르다. 안정적이다. 그런데 사용 설정이 어렵다. 그리고 Ctrl+S를 엄청 누르는 사용자입장에서 구매하라는 문구가 자주 뜬다. 물론 정품쓰면 좋겠지만 솔직히 나한테는 많이 비싸다. 그것이 ATOM으로 갈아탄 이유가 되었다.

보기에도 좋고 속도도 빠른데, 저장할때 성가시다.

3. Notepad++

NotepadppPortable

기능도 풍부하고, 빠르고 안정적이다. 다좋은데 세월을 알려주는 겉모습에서 깔자마자 지우게 만든다.

모양이 마음에 들지 않는다.

결론 : ATOM을 씁시다.

QIIME 설치하기

출처:http://qiime.org/install/install.html

가능하면 가상 머신을 이용해서 native 설치를 피하는 것을 권장합니다.

파이썬 2.7버전 Anaconda 패키지가 설치되어 있는 상태에서 진행.

터미널을 열고

sudo apt-get install build-essential python-dev python-pip
pip install numpy
pip install qiime
print_qiime_config.py -t

참고: numpy 는 이미 anaconda에 포함 되어 있어서 설치가 안된다.

print_qiime_config.py t 후 에러가 생기지 않는다면 설치 완료

리눅스에서 iPython 환경 구축 (Anaconda + Biopython)

윈도우에서는 winpython을 사용해서 하는 것이 여러모로 간편하다.

다운로드 받아서 압축만 풀면 되니, 리눅스에서는 조금 복잡한데

가장 쉬운 방법으로 정리 했다.

  1.  https://store.continuum.io/cshop/anaconda/
    아나콘다를 다운로드 받음( 약 300MB)
  2.   다운받은 폴더에서 터미널을 열고,
    bash Anaconda-2.x.x-Linux-x86[_64].sh
    (다운받은 파일명으로 수정해서 사용해야 한다.)
  3.  나오는 설명을 읽으면서 진행.
  4.  설치 후 터미널을 다시 켜야한다.
  5.  Biopython 설치는
    conda install biopython
  6. 이제 터미널에서 ipthon notebook으로 실행