티스토리 뷰

Language/Python

python matplot으로 차트 그리기

KyeongRok Kim 2018. 1. 21. 10:07

python matplot으로 차트 그리기

import numpy as np
import matplotlib.pylab as plt

x = np.array([1, 2, 3])
y = np.array([1, 2, 3])

plt.plot(x, y)
plt.show()

결과

 

pandas에서 column뽑아서 그리기

plt.plot(df['createDate'], df['reviewScore'])
plt.show()

 

x축 틱(Tick)이 두개인 그래프

import matplotlib.pyplot as plt

y = [22222, 22333]
x = [2020, 2021]

plt.xticks([2020, 2021])
plt.bar(x, y)

 

 

y축 포메팅

from matplotlib.ticker import FormatStrFormatter

df2020 = df.loc['2020-01-01':'2020-03-31']
df2021 = df.loc['2021-01-01':'2021-03-31']

y = [int(df2020['거래량'].sum()),
 int(df2021['거래량'].sum())]
x = [2020, 2021]

fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(FormatStrFormatter('%.0fkg'))
plt.title('2020, 2021 1~3월 거래량')
plt.xticks([2020, 2021], labels=['2020.1to3', '2021.1to3'])
plt.bar(x, y)

 

 

이중 축 그래프

import matplotlib.pyplot as plt

x = [1, 2, 3]
y = [2, 3, 4]
z = [100, 50, 0]

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
plt.title('x, y, z')
fig.set_size_inches([5, 5])
ax1.bar(x, y, color='g')
ax2.plot(x, z, color='r')

 

 

이중축 그래프2

 

df2020 = df.loc['2020-01-01':'2020-03-31']
df2021 = df.loc['2021-01-01':'2021-03-31']

y = [int(df2020['거래량'].sum()),
 int(df2021['거래량'].sum())]
y2 = [df2020['거래가격'].mean(), df2021['거래가격'].mean()]
x = [2020, 2021]

fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(FormatStrFormatter('%.0f단'))
plt.title('2020, 2021 1~3월 거래량')
plt.xticks([2020, 2021], labels=['2020.1to3', '2021.1to3'])
plt.bar(x, y)
ax2 = ax.twinx()
ax2.plot(x, y2, color='deeppink')

 

Sub plot그리기

plt 오브젝트에 subplot을 만들어서 여러개의 그래프를 그릴 수 있습니다.

 

위와 같이 2 * 2 형태의 그리드를 만들고 1, 2, 3, 4 분면에 그래프를 넣는 것입니다.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 10)

y1 = x
y2 = x**2
y3 = x**3
y4 = np.sqrt(x)

plt.figure()
plt.subplot(2,2,1)

여기까지 하면 위와 같이 한개의 그래프만 생깁니다.

plt.plot(x, y1, 'ro')
plt.title('y1=x')

그래프를 그려줍니다. 'ro'에서 r은 red이고 o는 위 처럼 점으로 찍으라는 뜻입니다.

plt.subplot(2,2,2)
plt.plot(x, y2, 'g--')
plt.title('y2=x^2')

plt.subplot(2,2,3)
plt.plot(x, y3, 'b^')
plt.title('y2=x^3')

plt.subplot(2,2,4)
plt.plot(x, y3, 'ks')
plt.title('y2=sqrt(x)')

위와같이 옵션을 바꿔가면서 3개의 그래프를 추가로 그렸습니다.

 

 

위와같이 4 * 1 형태로도 가능합니다. 아래 코드를 참고하세요.

plt.subplot(4,1,1)
plt.plot(x, y1, 'ro')
plt.title('y1=x')

plt.subplot(4,1,2)
plt.plot(x, y2, 'g--')
plt.title('y2=x^2')

plt.subplot(4,1,3)
plt.plot(x, y3, 'b^')
plt.title('y2=x^3')

plt.subplot(4,1,4)
plt.plot(x, y3, 'ks')
plt.title('y2=sqrt(x)')

 

두개 항목 그래프 그리기

ggplot스타일 적용하면 그래프가 조금 더 예쁩니다.

plt.style.use('ggplot')
fig, ax1 = plt.subplots()
gr1 = df[['거래량', '거래가격']].groupby(pd.Grouper(freq='m'))
gr1.sum()[['거래량', '거래가격']].plot(kind='bar', ax=ax1)

groupby한 데이터에 sum()을 한 후 .plot()을 할 때 ax파라메터를 넘기면 어떤 영역에 그려질지 정할 수 있습니다.

 

 

y축 추가, 범례 적용

 

plt.style.use('ggplot')
# plt.style.use('dark_background')

fig, ax1 = plt.subplots()
plt.title('2020, 2021 1~3거래량과 가격')
ax2 = ax1.twinx()
# fig.autofmt_xdate()
gr1 = df[['거래량', '거래가격']].groupby(pd.Grouper(freq='m'))
# gr1.sum().plot(secondary_y=True, kind='line')
gr1.sum()['거래량'].plot(kind='line', ax=ax1, c='g', label='거래량')
gr1.mean()['거래가격'].plot(kind='line', ax=ax2, c='deeppink', label='거래가격')
ax1.legend(bbox_to_anchor =(0.75, 1.15), ncol = 2)
ax2.legend(bbox_to_anchor =(1.0, 1.15), ncol = 2)

 

 

fig, ax1 = plt.subplots()
plt.title('2020.1 ~ 2021.3 거래량과 가격 평균')
ax2 = ax1.twinx()
fig.autofmt_xdate()
gr1 = df[['거래량', '거래가격']].groupby(pd.Grouper(freq='m'))
gr1.mean()['거래량'].plot(kind='line', ax=ax1, c='g', label='거래량')
gr1.mean()['거래가격'].plot(kind='line', ax=ax2, c='deeppink', label='평균거래가격')
ax1.legend(bbox_to_anchor =(0.65, 1.2), ncol = 2)
ax2.legend(bbox_to_anchor =(1.0, 1.2), ncol = 2)

 

end.

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함