본문 바로가기

Data/Python

Machine Learning #5 Matplotlib

1. Default


import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

#t = np.arange(0., 5., 0.2)
#plt.plot(t, t,'r--', t, 0.5*t**2, 'bs:', 0.2*t**3, 'g^-')

np.random.seed(12345)


f1 = plt.figure(figsize=(10,2))
plt.title('figsize:(10,2)')
plt.plot(np.random.randn(100))
plt.savefig('ex_plot.png', dpi=400, bbox_inches='tight')
plt.show()




2. Line Ex

x1 = np.linspace(0., 5.)
x2 = np.linspace(0., 2.)
y1 = np.cos(2*np.pi*x1)*np.exp(-x1)
y2 = np.cos(2*np.pi*x2)

ax1 = plt.subplot(3,1,1)
plt.plot(x1,y1,'yo-')
plt.title('3 1 1')
plt.ylabel("y value")

ax2 = plt.subplot(3,1,2)
plt.plot(x2,y2,'r.-')
plt.title('3 1 2')
plt.ylabel("y value")

ax3 = plt.subplot(3,1,3)
plt.plot(x2,y2,'r.-')
plt.title('3 1 3')
plt.ylabel("y value")

plt.tight_layout()
plt.savefig('ex2_plot.png', dpi=400, bbox_inches='tight')
plt.show()




3. Bar Plot


plt.style.use('ggplot')

customers = ['ABC', 'DEF', 'GHI', 'JKL', 'MNO']
customers_index = range(len(customers)) # x
sale_amount = [127, 90, 201, 111, 232] # y

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.bar(customers_index, sale_amount, align='center', color='darkblue')
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')

plt.xticks(customers_index, customers, rotation=0, fontsize='small')

plt.xlabel('Customer Name')
plt.ylabel('Sale Amount')
plt.title('Sale Amount Bar Graph')

plt.savefig('bar_plot.png', dpi=400, bbox_inches='tight')
plt.show()



4. Histogram


mu1, mu2, sigma = 100, 130, 15

x1 = mu1 + sigma*np.random.randn(10000)
x2 = mu2 + sigma*np.random.randn(10000)

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
n, bins, patches = ax1.hist(x1, bins=50, normed=False, color='darkgreen')
n, bins, patches = ax1.hist(x2, bins=50, normed=False, color='orange', alpha=0.5)

ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')

plt.xlabel('Bins')
plt.ylabel('Number of Values in Bin')
fig.suptitle('Histograms', fontsize=14, fontweight='bold')
ax1.set_title('Two Frequency Distributions')

plt.savefig('histogram.png', dpi=400, bbox_inches='tight')
plt.show()



5. Line Plot


plot_data1 = np.random.randn(50).cumsum()
plot_data2 = np.random.randn(50).cumsum()
plot_data3 = np.random.randn(50).cumsum()
plot_data4 = np.random.randn(50).cumsum()

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.plot(plot_data1, marker='o', color='blue', linestyle='-', label = 'Blue Solid')
ax1.plot(plot_data2, marker='+', color='red', linestyle='--', label = 'Red Dashed')
ax1.plot(plot_data3, marker='*', color='green', linestyle='-.', label = 'Green Dash Dot')
ax1.plot(plot_data4, marker='s', color='orange', linestyle=':', label = 'Orange Dotted')
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')

ax1.set_title('Line Plots: Markers, Colors, and Linestyles')
plt.xlabel('Draw')
plt.ylabel('Random Number')
plt.legend(loc='best')

plt.savefig('line_plot.png', dpi=400, bbox_inches='tight')
plt.show()



6. Line Plot2


x = np.arange(start=1., stop=15., step=1.)
y_linear = x + 5. * np.random.randn(14)
y_quadratic = x**2 + 10. * np.random.randn(14)

fn_linear = np.poly1d(np.polyfit(x, y_linear, deg=1))
fn_quadratic = np.poly1d(np.polyfit(x, y_quadratic, deg=2))

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.plot(x, y_linear, 'bo', x, y_quadratic, 'go', \
x, fn_linear(x), 'b-', x, fn_quadratic(x), 'g-', linewidth=2.)
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')

ax1.set_title('Scatter Plots with Bet Fit Lines')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.xlim((min(x)-1., max(x)+1.))
plt.ylim((min(y_quadratic)-10., max(y_quadratic)+10.))

plt.savefig('line_plot.png', dpi=400, bbox_inches='tight')
plt.show()



7. Pandas Plot


fig, axes = plt.subplots(nrows=1, ncols=2)
ax1, ax2 = axes.ravel()

data_frame = pd.DataFrame(np.random.rand(5,3),
index=['Customer1','Customer2','Customer3','Customer4','Customer5'],
columns=pd.Index(['Metric1', 'Metric2','Metric3'], name='Metrics'))

data_frame.plot(kind='bar', ax=ax1, alpha=0.75, title="Bar Plot")
plt.setp(ax1.get_xticklabels(), rotation=45, fontsize=10)
plt.setp(ax1.get_yticklabels(), rotation=0, fontsize=10)
ax1.set_xlabel('Customer')
ax1.set_ylabel('Value')
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')

colors = dict(boxes='DarkBlue', whiskers='Gray', medians='Red', caps='Black')
data_frame.plot(kind='box', color=colors, sym='r', ax=ax2, title="Box Plot")
plt.setp(ax1.get_xticklabels(), rotation=45, fontsize=10)
plt.setp(ax1.get_yticklabels(), rotation=0, fontsize=10)
ax1.set_xlabel('Metrics')
ax1.set_ylabel('Value')
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')

plt.savefig('pandas_plot.png', dpi=400, bbox_inches='tight')
plt.show()


반응형

'Data > Python' 카테고리의 다른 글

[Anaconda] 아나콘다 설치 및 사용법 for 맥 & 윈도우  (0) 2018.09.27
Machine Learning #6 Pandas Dataframe  (0) 2018.09.20
Machine Learning #4 Pandas  (0) 2018.09.19
Machine Learning #3 numpy  (0) 2018.09.19
Machine Learning #2 python  (0) 2018.09.18