도표 설명(legend)의 위치는 못 바꾸는 건가요
조회수 20998회
발생하는 문제 및 실행환경
점이 20개 정도 찍힌 그래프를 만들고 있는데 legend가 자꾸 그래프 안으로 들어와서 거슬립니다.
축이나 그래프의 크기를 바꾸지 않는 선에서 legend를 그래프의 바깥에 놓고(오른쪽), legend안에 폰트 크기도 줄이고 싶습니다.
legend 위치랑 폰트 크기를 바꾸는 함수는 어디있나요?
1 답변
-
여러 가지 방법이 있겠지만, 제가 알기로는
legend
를 그래프 바깥에 두거나 폰트 크기를 바꿀 때는bbox_to_anchor
키워드를 주로 씁니다.먼저 legend의 위치를 옮기는 법부터 쓰면
import matplotlib.pyplot as plt import numpy as np x = np.arange(10) fig = plt.figure() ax = plt.subplot(111) for i in xrange(5): ax.plot(x, i * x, label='$y = %ix$' % i) ax.legend() plt.show()
이렇게 legend가 그래프를 가릴 경우
bbox_to_anchor
를 써서 legend의 위치를 바꿀 수 있습니다.import matplotlib.pyplot as plt import numpy as np x = np.arange(10) fig = plt.figure() ax = plt.subplot(111) for i in xrange(5): ax.plot(x, i * x, label='$y = %ix$' % i) ax.legend(bbox_to_anchor=(1.1, 1.05)) plt.show()
완벽하진 않은데 legend가 1시 방향으로 움직였지요. 비슷하게, legend를 수평으로 맞춰서 그래프의 맨 위에 놓는 방법은 다음과 같습니다. *추가로 legend 박스를 둥글게 처리하고 음영도 줬습니다
import matplotlib.pyplot as plt import numpy as np x = np.arange(10) fig = plt.figure() ax = plt.subplot(111) for i in xrange(5): line, = ax.plot(x, i * x, label='$y = %ix$'%i) ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05), ncol=3, fancybox=True, shadow=True) plt.show()
그래프의 크기를 조절해서 legend를 완전히 축 바깥에 놓는 것도 가능합니다
import matplotlib.pyplot as plt import numpy as np x = np.arange(10) fig = plt.figure() ax = plt.subplot(111) for i in xrange(5): ax.plot(x, i * x, label='$y = %ix$'%i) # Shrink current axis by 20% box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) # Put a legend to the right of the current axis ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.show()
수평 때랑 비슷하게, legend box를 세로 방향으로 줄여 그래프 밑에 legend를 두는 방법도 있습니다
import matplotlib.pyplot as plt import numpy as np x = np.arange(10) fig = plt.figure() ax = plt.subplot(111) for i in xrange(5): line, = ax.plot(x, i * x, label='$y = %ix$'%i) # Shrink current axis's height by 10% on the bottom box = ax.get_position() ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9]) # Put a legend below current axis ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), fancybox=True, shadow=True, ncol=5) plt.show()
더 자세한건 matplotlib legend guide를 참고해주세요
댓글 입력