본문 바로가기

Programing Language/Python

[matplotlib] Dashes 완벽공략

반응형

Dashes

왜인지 모르겠지만, matplotlib 공식 문서에 있는 dashes 설명이 살짝 부족하다. 그래서, 매번 쓸 때 마다 검색하는데, 스스로를 위한 참고용으로 남겨놓는다.

Method

dash_style1 = (<length on>, <length off>)
dash_style2 = (<length on>, <length off>, <length on>, <length off>)
dash_style3 = (<offset>, (<length on>, <length off>))
dash_style4 = (<offset>, (<length on>, <length off>, <length on>, <length off>, <length on>, <length off>))
plt.plot(x, y, dashes=dashe_style1)
plt.hlines(y, xmin, xmax, dashes=dashe_style3)
  • hlines와 같은 함수에서는 plot에서 쓰는 dashes 옵션이 먹히지 않는다. 맨 앞에 offset을 추가해 주어야 함
  • dash_style3tupletuple임을 유의

Example

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 500)
y = np.sin(x)

plt.rc('lines', linewidth=2.5)
fig, ax = plt.subplots()

# Using set_dashes() and set_capstyle() to modify dashing of an existing line.
line1, = ax.plot(x, y, label='Using set_dashes() and set_dash_capstyle()')
line1.set_dashes([2, 2, 10, 2])  # 2pt line, 2pt break, 10pt line, 2pt break.
line1.set_dash_capstyle('round')

# Using plot(..., dashes=...) to set the dashing when creating a line.
line2, = ax.plot(x, y - 0.2, dashes=[6, 2], label='Using the dashes parameter')

# Using plot(..., dashes=..., gapcolor=...) to set the dashing and
# alternating color when creating a line.
line3, = ax.plot(x, y - 0.4, dashes=[4, 4], gapcolor='tab:pink',
                 label='Using the dashes and gapcolor parameters')


# Using hlines(..., dashes=...) to set the dashing with a offset.
line4 = plt.hlines(0, x[0], x[-1], dashes=(0, (1,4,1,2)), color='grey', zorder=-10)
line4.set_dashes((0, [4,1]))

ax.legend(handlelength=8)
plt.show()
  • 위의 예제에서 line1-3Line2D 객체이고, line4는 LineCollection 객체
  • LineCollection에서는 set_dash_capstyle 혹은 gapcolor가 작동하지 않음에 유의

반응형