이것저것 코드/파이썬
[파이썬] 꺾은선 그래프 그리기 (토끼그림)
원-스텝
2022. 9. 8. 18:05
반응형
그래프를 그려보자
우측 코드의 빈 부분을 채워서 꺾은선 그래프를 완성하세요.
여러분이 작성해야 할 코드는 다음과 같습니다.
font의 NanumBarunGothic.ttf 폰트를 저장하여 그래프에 한글 폰트 적용하기
data.py 모듈을 import 하여 x축, y축 데이터 가져오기
꺾은선 그래프 그리기
# 초기 코드
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from elice_utils import EliceUtils
elice_utils = EliceUtils()
# 한글 폰트를 적용합니다.
font = None
# x축과 y축의 데이터를 저장하세요,
x = None
y = None
# 꺾은선 그래프를 그립니다.
# 아래의 코드는 수정하지 마세요.
# 그래프의 제목을 지정합니다.
plt.title('본격! 프로그래밍', fontproperties=font)
# 엘리스 화면에 그래프를 표시합니다.
plt.savefig('graph.png')
elice_utils.send_image('graph.png')
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from elice_utils import EliceUtils
elice_utils = EliceUtils()
# 한글 폰트를 적용합니다.
path = './NanumBarunGothic.ttf'
font = fm.FontProperties(fname=path)
import data
# x축과 y축의 데이터를 저장하세요,
x = data.get_x_data()
y = data.get_y_data()
# 꺾은선 그래프를 그립니다.
plt.plot(x, y)
plt.show()
# 아래의 코드는 수정하지 마세요.
# 그래프의 제목을 지정합니다.
plt.title('본격! 프로그래밍', fontproperties=font)
# 엘리스 화면에 그래프를 표시합니다.
plt.savefig('graph.png')
elice_utils.send_image('graph.png')
# data.py
def get_x_data():
x = [-5, -6, -7, -7, -6, -5, -5, -7, -9, -10, -11, -11, -9, -8, -6, -4, -2, 0, 2, 4, 6, 8, 9, 11, 11, 10, 9, 7, 5, 5, 6, 7, 7, 6, 5, 2, -2, -5, -6, -7, -8, -9, -9, -8, -7, -6, -5, -7, -8, -8, -7, -4, 4, 7, 8, 8, 7, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, None, 3, 3, 4, 6, 8, 9, 9, 8, 7, 5, 3, None, -3, -3, -4, -6, -8, -9, -9, -8, -7, -5, -3, None, 1, 1, 2, 2, None, -1, -1, -2, -2, None, 0, 1, 0, -1, 0, 0, None, 3, 9, None, 3, 9, None, -3, -9, None, -3, -9, None, 7, 8, 10, 10, 9, 2, 1, 1, None, -7, -8, -10, -10, -9, -2, -1, -1, None, 0, 1, 2, 3, 3, 2, 1, 0, -1, -2, -3, -3, -2, -1, 0, 0, None]
return x
def get_y_data():
y = [-5, -4, -2, -1, 1, 2, 3, 5, 8, 10, 13, 15, 17, 17, 15, 12, 8, 3, 8, 12, 15, 17, 17, 15, 13, 10, 8, 5, 3, 2, 1, -1, -2, -4, -5, -6, -6, -5, -5, -4, -4, -5, -7, -8, -8, -7, -7, -9, -11, -13, -15, -16, -16, -15, -13, -11, -9, -7, -7, -8, -8, -7, -5, -4, -4, -5, -5, None, 3, 5, 8, 13, 15, 15, 13, 10, 8, 5, 3, None, 3, 5, 8, 13, 15, 15, 13, 10, 8, 5, 3, None, -2, -1, -1, -2, None, -2, -1, -1, -2, None, -3, -3, -2, -3, -3, -6, None, -3, -2, None, -4, -3, None, -3, -2, None, -4, -3, None, -15, -15, -16, -17, -18, -18, -17, -16, None, -15, -15, -16, -17, -18, -18, -17, -16, None, 0, 1, 1, 0, -1, -2, -2, -1, -2, -2, -1, 0, 1, 1, 0, -1 , None]
return y
# elice utils
# elice-utils
# maintainer: Suin Kim (suin@elicer.com) and Jungkook Park (jk@elicer.com)
import base64
import mimetypes
import os
import urllib.parse
import urllib.request
class EliceUtils(object):
def __init__(self):
self._execution_token = os.getenv('EXECUTION_TOKEN')
self._executor_ip = os.getenv('EXECUTOR_IP')
self._executor_com_port = os.getenv('EXECUTOR_COM_PORT')
self._otp_key = None
self._local_mode = False
if not all((self._execution_token, self._executor_ip, self._executor_com_port)):
self._local_mode = True
print('=== NON-ELICE ENVIRONMENT ===')
print('Warning: This script is running on the non-elice environment. '
'All outputs will be redirected to standard output.')
print('=============================')
def _send(self, url, data):
if self._local_mode:
msg_type = data['type']
msg_data = data['data']
if msg_type in ['grader', 'score']:
print('[%s] %s' % (msg_type, msg_data), end='')
else:
print('[%s]' % msg_type, end='')
return
data_encoded = urllib.parse.urlencode(data)
q = urllib.request.Request(url,
data=data_encoded.encode('utf-8'))
try:
urllib.request.urlopen(q)
except Exception:
raise Exception('Failed to send message to elice.')
def _handle_image(self, filepath):
mtype, _ = mimetypes.guess_type(filepath)
if mtype is None or not mtype.startswith('image/'):
raise ValueError('Invalid image filepath.')
with open(filepath, 'rb') as f:
data = 'data:%s;base64,%s' % (
mtype,
base64.b64encode(f.read()).decode('utf-8')
)
return data
def _handle_file(self, filepath):
mtype, _ = mimetypes.guess_type(filepath)
with open(filepath, 'rb') as f:
data = '%s;data:%s;base64,%s' % (
os.path.basename(filepath),
mtype or 'application/octet-stream',
base64.b64encode(f.read()).decode('utf-8')
)
return data
def send(self, msg_type, msg_data):
self._send(
'http://%s:%s/comm/send/%s' % (self._executor_ip,
self._executor_com_port,
self._execution_token),
{'type': msg_type, 'data': msg_data}
)
def send_image(self, filepath):
self.send('image', self._handle_image(filepath))
def send_file(self, filepath):
self.send('file', self._handle_file(filepath))
def secure_init(self):
if self._local_mode:
return
try:
r = urllib.request.urlopen(
'http://%s:%s/comm/secure/init/%s' % (self._executor_ip,
self._executor_com_port,
self._execution_token)
)
except Exception:
raise Exception('Failed to initialize elice util secure channel.')
self._otp_key = r.read().decode('utf-8')
def secure_send(self, msg_type, msg_data):
self._send(
'http://%s:%s/comm/secure/send/%s/%s' % (self._executor_ip,
self._executor_com_port,
self._execution_token,
self._otp_key),
{'type': msg_type, 'data': msg_data}
)
def secure_send_image(self, filepath):
self.secure_send('image', self._handle_image(filepath))
def secure_send_file(self, filepath):
self.secure_send('file', self._handle_file(filepath))
def secure_send_grader(self, msg):
self.secure_send('grader', msg)
def secure_send_score(self, score):
self.secure_send('score', score)
반응형