[matplotlib] 그래프 색상/마커 다르게 그리기

2023. 9. 18. 14:34·프로그래밍 Programming/파이썬 Python

그래프를 여러개 그리는데 색깔이 설정에서 계속 동일하게 반복된다. (아래 그림 참고)

나의 경우에는 색상을 classic으로 설정해서 클래식 색상의 7가지가 반복되게 되어있다.

 

 

이게 마음에 안 들어서 살펴보다가 최신 matplotlib 버전부터는 axes.set_prop_cycle을 이용하면 색상도 편하게 다르게 할 수 있고 마커도 일정 패턴을 반복하도록 할 수 있음을 알게 되었다.

 

아래는 그 예시 코드로 Spectral cmap에서 내가 원하는 그래프 개수만큼을 간격을 추출해서

그래프를 그리기 전에 미리 cycler를 정의해놓으면 편하게 색상을 지정할 수 있다.

 

import matplotlib.pyplot as plt

ax = plt.subplot(111)
num_lines = 30

colors = [plt.cm.Spectral(i) for i in np.linspace(0, 1, num_lines)]

from cycler import cycler
ax.set_prop_cycle(cycler('color', colors))

for n in range(num_lines):
    x = np.linspace(0,10,500)
    y = np.sin(x)+n
    ax.plot(x, y, lw=3)

plt.show()

 

 

마커까지 설정하고 싶으면 아래 코드 처럼 color이외에도 marker를 설정하면된다.

아래의 예시는 linestyle과 linewidth를 바꾼 예시이다.

x = np.linspace(0, 2 * np.pi, 50)
offsets = np.linspace(0, 2 * np.pi, 4, endpoint=False)
yy = np.transpose(np.array([np.sin(x + phi) for phi in offsets]))

default_cycler = (cycler(color=['r', 'g', 'b', 'y']) +
                  cycler(linestyle=['-', '--', ':', '-.']))

custom_cycler = (cycler(color=['c', 'm', 'y', 'k']) +
                 cycler(lw=[1, 2, 3, 4]))

fig, (ax0, ax1) = plt.subplots(nrows=2)
ax0.plot(yy)
ax0.set_title('Set default color cycle to rgby')
ax0.set_prop_cycle(default_cycler)
ax1.set_prop_cycle(custom_cycler)
ax1.plot(yy)
ax1.set_title('Set axes color cycle to cmyk')

# Add a bit more space between the two plots.
fig.subplots_adjust(hspace=0.3)
plt.show()

 

 

matplotlib이 보유한 cmap 종류

cmaps = [('Perceptually Uniform Sequential', [
            'viridis', 'plasma', 'inferno', 'magma', 'cividis']),
         ('Sequential', [
            'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
            'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
            'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']),
         ('Sequential (2)', [
            'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink',
            'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',
            'hot', 'afmhot', 'gist_heat', 'copper']),
         ('Diverging', [
            'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
            'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic']),
         ('Cyclic', ['twilight', 'twilight_shifted', 'hsv']),
         ('Qualitative', [
            'Pastel1', 'Pastel2', 'Paired', 'Accent',
            'Dark2', 'Set1', 'Set2', 'Set3',
            'tab10', 'tab20', 'tab20b', 'tab20c']),
         ('Miscellaneous', [
            'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
            'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg',
            'gist_rainbow', 'rainbow', 'jet', 'turbo', 'nipy_spectral',
            'gist_ncar'])]

색상 표는 다음 링크에서 확인

 


https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_prop_cycle.html

저작자표시 비영리 변경금지 (새창열림)

'프로그래밍 Programming > 파이썬 Python' 카테고리의 다른 글

[python] Visual studio code에서 다운받은 패키지 사용하기(경로 설정 등)  (0) 2024.04.16
[matplotlib] matplotlib에서 latex 사용 오류  (0) 2024.01.26
[Python] MCMC Sampling library  (0) 2023.08.24
[Jupyter notebook] 내가 설정한 주피터 노트북 테마  (0) 2023.02.23
[JAX] JAX 설치 및 GPU 사용하기  (2) 2023.02.09
'프로그래밍 Programming/파이썬 Python' 카테고리의 다른 글
  • [python] Visual studio code에서 다운받은 패키지 사용하기(경로 설정 등)
  • [matplotlib] matplotlib에서 latex 사용 오류
  • [Python] MCMC Sampling library
  • [Jupyter notebook] 내가 설정한 주피터 노트북 테마
보통의공대생
보통의공대생
수학,프로그래밍,기계항공우주 등 공부하는 기록들을 남깁니다.
  • 보통의공대생
    뛰는 놈 위에 나는 공대생
    보통의공대생
  • 전체
    오늘
    어제
    • 분류 전체보기 (459) N
      • 공지 (1)
      • 영어 공부 English Study (40)
        • 텝스 TEPS (7)
        • 글 Article (21)
        • 영상 Video (10)
      • 연구 Research (99)
        • 최적화 Optimization (3)
        • 데이터과학 Data Science (7)
        • 인공지능 Artificial Intelligent (40)
        • 제어 Control (45)
      • 프로그래밍 Programming (103)
        • 매트랩 MATLAB (25)
        • 파이썬 Python (33)
        • 줄리아 Julia (2)
        • C++ (3)
        • 리눅스 우분투 Ubuntu (6)
      • 항공우주 Aeronautical engineeri.. (21)
        • 항법 Navigation (0)
        • 유도 Guidance (0)
      • 기계공학 Mechanical engineering (13)
        • 열역학 Thermodynamics (0)
        • 고체역학 Statics & Solid mechan.. (10)
        • 동역학 Dynamics (1)
        • 유체역학 Fluid Dynamics (0)
      • 수학 Mathematics (34)
        • 선형대수학 Linear Algebra (18)
        • 미분방정식 Differential Equation (3)
        • 확률및통계 Probability & Sta.. (2)
        • 미적분학 Calculus (1)
        • 복소해석학 Complex Analysis (5)
        • 실해석학 Real Analysis (0)
      • 수치해석 Numerical Analysis (21)
      • 확률 및 랜덤프로세스 Random process (2)
      • 추론 & 추정 이론 Estimation (3)
      • 기타 (26)
        • 설계 프로젝트 System Design (8)
        • 논문작성 Writing (55)
        • 세미나 Seminar (2)
        • 생산성 Productivity (3)
      • 유학 생활 Daily (6)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Dear abby
    논문작성
    Python
    IEEE
    pytorch
    Julia
    옵시디언
    텝스
    딥러닝
    고체역학
    JAX
    Numerical Analysis
    LaTeX
    에러기록
    Zotero
    obsidian
    생산성
    Statics
    수치해석
    teps
    ChatGPT
    Linear algebra
    서버
    우분투
    MATLAB
    WOX
    matplotlib
    텝스공부
    논문작성법
    인공지능
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
보통의공대생
[matplotlib] 그래프 색상/마커 다르게 그리기
상단으로

티스토리툴바