matplotlib 간단한 실습

2018. 1. 2. 12:38분석 Python/Visualization

728x90
from collections import Counter

from matplotlib import pyplot as plt

import numpy as np

years = [1950,1960,1970,1980,1990,2000,2010]

gdp = [300.2,543.3,1075.9,2862.5,5979.5,10234.2, 15234.4]



plt.plot(years,gdp,color="green",marker="o",linestyle="solid")

plt.ylabel("billionsof $")

plt.show()

# 막대 그래프

movies =["a","b","c","d","e"]

num_oscars=[5,11,3,6,10]



# 막대 너비 default 0.8

# 막대가 가운데로 올수 있도록 왼쪽 좌표에 0.1씩 더하기

xs=[i + 0.1 for i ,_ in enumerate(movies)]

plt.bar(xs,num_oscars)

matplotlib실습_180102.py
다운로드

 

plt.ylabel("of academy awards")

plt.title("my favorite movies")

# 막대의 가운데에 영화 제목 레이블 달기

plt.xticks([ i+0.1 for i ,_ in enumerate(movies)],movies)

plt.show()

## 히스토그램

grades = np.round(np.random.uniform(40,100,10),0)

decile = lambda grade : grade //10 *10

histogram =Counter(decile(grade) for grade in grades)

plt.bar([x for x in histogram.keys()],histogram.values(),8)

plt.axis([-5,105,0,5])

plt.xticks([10*i for i in range(11)])

plt.xlabel("decile")

plt.ylabel("# of students")

plt.title("distribution of exam 1 grades")

plt.show()

## 차이가 눈에 띄게 보임

mentions=[500,505]

years =[2013,2014]

plt.bar([2013 , 2014],mentions,0.8)

plt.xticks(years)

plt.ylabel("# of times i heard someone say 'data science'")

# 이렇게 하지 않으면 x 축에 0,1 label 생성되서 

# 주변 어딘가에 2.013e3 라고 표기가 된다고 한다.

plt.ticklabel_format(useoffset=False)

# 오해를 불러 일으키는 y 축 500 이상만 보여주기

plt.axis([2012.5,2014.5,499,506])

plt.title("look at the 'huge' increase!")

plt.show()

 

 

## 차이가 안보임

mentions=[500,505]

years =[2013,2014]

plt.bar([2013 , 2014],mentions,0.8)

plt.xticks(years)

plt.ylabel("# of times i heard someone say 'data science'")

# 이렇게 하지 않으면 x 축에 0,1 label 생성되서 

# 주변 어딘가에 2.013e3 라고 표기가 된다고 한다.

plt.ticklabel_format(useoffset=False)

plt.axis([2012.5,2014.5,0,550])

plt.title("not so huge anymore")

plt.show()

 

 

 

# 선그래프



variance=[1,2,4,8,16,32,64,128,256]

bias_squared=[256,128,64,32,16,8,4,2,1]

total_error =[x+y for x,y in zip(variance,bias_squared)]

xs = [ i for i , _ in enumerate(variance)]

plt.plot(xs,variance,'g-',label="variance")

plt.plot(xs,bias_squared,'r-',label="bias^2")

plt.plot(xs,total_error,'b:',label="total_error")

# 각 series에 label 미리 설정해 놨기 때문에

# legend(범례) 어렵지 않게 가능

# 여기서 loc=9는 top center 을 의미한다

plt.legend(loc=9)

plt.xlabel("model complexity")

plt.title("the bias-variance tradeoff")

plt.show()

 

# 3-4 산점도 

# 두 변수간 연관 관계를 보여주고 싶을때 적합한 형태의 그래프

# 사용자 친구 수와 그들이 메일 사이트에서 체류하는 시간 사이 연관성

#

friends =[70,65,72,63,71,64,54,67,59]

minutes=[175,170,205,120,220,130,105,145,190]

labels=[i for _,i in enumerate("abcdefghi")]

plt.scatter(friends,minutes)

for label, friend_count, minute_count in zip(labels,friends,minutes):

    plt.annotate(label,xy=(friend_count,minute_count),

    xytext=(5,-5),

    textcoords="offset points")

plt.title("daily minutes vs. number of friends")

plt.xlabel("# of friends")

plt.ylabel("daily minutes spent on the site")

plt.show()

 

 

## plt.axis(equal) 사용하면 공정한 비교 가능하다 

test_1=[99,90,85,97,80]

test_2=[100,85,60,90,70]

plt.scatter(test_1,test_2)

plt.title("axes are comparable")

plt.xlabel("test_1")

plt.ylabel("test_2")

plt.axis("equal")

plt.show()

 

## 추가적 공부한다면 seaborn , D3.js(웹을 위한 시각화), ggplot(R에서도 많이 사용) 

728x90