matplotlib¶
matplotlib.pyplot 라이브러리 import
In [1]:
import matplotlib.pyplot as plt
Bar¶
- show how some quantity varies
In [10]:
plt.bar([1,3,0,10], [10,23,30,1])
plt.show()
width¶
- default = 0.8 (기본 0.8로 설정되어 있음)
In [11]:
plt.bar([1,2,3,4,5],[10,20,30,40,50], width=0.1)
plt.show()
Bar의 위치 변경¶
In [12]:
def make_chart_simple_bar_chart():
movies = ["Annie Hall", "Ben-hur", "Casablanca", "Gandhi"]
num_oscars = [5, 11, 3, 8]
#left coordinates so that each bar is centered
xs = [i + 0.5 for i, _ in enumerate(movies)]
plt.bar(xs, num_oscars)
plt.ylabel("# of Academy Awards")
plt.xlabel("My Favorite Movies")
plt.title("My Favorite Movies")
plt.xticks([i for i,_ in enumerate(movies)], movies)
plt.show()
make_chart_simple_bar_chart()
점수분포 Bar 예제¶
In [13]:
from collections import Counter
def make_chart_histogram():
grades = [83, 95, 91, 87, 70, 0, 85, 82, 100, 67, 73, 77, 0]
decile = lambda x: (x // 10) * 10 # 십분위로 나타내기(1의 자리 버리기)
histogram = Counter(decile(grade) for grade in grades)
# print(decile)
# print(histogram)
#left coordinates so that each bar is centered
plt.bar([x+5 for x in histogram.keys()], histogram.values(), width = 0.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()
make_chart_histogram()
misleading at bar chart¶
- bar 그래프에서 일어날 수 있는 잘못된 chart 의 예
In [14]:
'''인자로 True 를 받으면 y축의 값을 차이가 별로 없게 확대(499~506)
False 를 받으면 정상적으로 y축의 값을 0~505 로 설정'''
def make_chart_misleading_y_axis(mislead=True):
mentions = [500, 505]
years = [2013, 2014]
plt.bar([2012.6,2013.6], mentions, 0.8)
plt.xticks(years)
plt.ylabel("# of times I heard someone say 'data science'")
if mislead:
#misleading y-axis only shows the part above 500
plt.axis([2012.5, 2014.5, 499, 506]) #bad
plt.title("misleading (Huge difference)")
else: #실제로는 5밖에 차이 안남
plt.axis([2012.5, 2014.5, 0, 550]) #good
plt.title("just 5 difference")
plt.show()
In [15]:
make_chart_misleading_y_axis(True)
In [16]:
make_chart_misleading_y_axis(False)