Matplotlib으로 어둠 모드에 맞는 그림 만들기

Matplotlib의 디스플레이 요소에 흰색 경계를 추가함으로써 같은 이미지 파일에서 오른쪽 모드(흰색 배경)와 어두운 모드(검은색 배경) 두 가지 모두 쉽게 표시할 수 있는 작도 방법을 총괄하였다.다음 예에서 보듯이 도면의 배경이 투명해도 선과 문자는 검은색 배경에 묻히지 않고 알기 쉬운 형태로 병존할 수 있습니다.
darkmode-compatible-figure-light.png
darkmode-compatible-figure-dark.png
조명 모드(흰색 배경)로 표시
검은색 배경으로 표시
Zenn의 제한으로 인해 HTML을 사용하여 배경색을 변경할 수 없습니다. 위의 예는 이미지 자체에 검은색 배경을 그리는 것입니다.실제 배경색에 따라 변화가 발생하는 상황을 보십시오여기..

Path effects


path effectsmatplotlib.patheffects를 사용하여 표시 요소(artists)에 경계선을 추가합니다.이름에서 알 수 있듯이 문자와 선그림 등 선(경로)이 있는 요소만 경계를 추가할 수 있다.이번에는 withStroke()에서 경계선 색상과 선폭을 설정한 path effect 대상을 제작했다.
요소에 경계 추가하기 설정
import matplotlib as plt
from matplotlib.patheffects import withStroke


border = withStroke(linewidth=3, foreground="white")

Examples


경계를 추가하려면 생성된 path effect 대상(1)을 rcParams 전역으로 설정하고, (2) 그림 관련 함수나 방법이 가지고 있는 path_effects 옵션을 사용하여 개별적으로 설정하거나, (3) 디스플레이 요소가 가지고 있는 set_path_effects() 방법을 사용하여 개별적으로 설정하십시오.다음은 (1)의 예를 소개한다.
모든 요소에 테두리를 추가할 때
with plt.rc_context({"path.effects": [border]}):
    plt.plot([1, 2, 1, 3], label="A")
    plt.plot([2, 1, 3, 2], label="B")
    plt.title("Darkmode-compatible figure")
    plt.legend()

plt.savefig("figure.png", transparent=True)
rcParams의 "path.effects"는 여러 설정을 받아들이기 때문에 "border"처럼 배열에 따라 교부합니다
rc_context () 를 사용하면 with 블록에 적힌 요소만 경계를 적용할 수 있습니다
위의 예는 그림의 외곽에도 경계를 추가해서 잘 보이지 않을 수도 있습니다.좀 복잡하지만 다음과 같은 방식으로 외주의 경계를 없앨 수 있다.
그림의 외곽에만 경계선을 추가하지 않을 때(추천?)
fig = plt.figure()

with plt.rc_context({"path.effects": [border]}):
    ax = fig.add_subplot()
    ax.plot([1, 2, 1, 3], label="A")
    ax.plot([2, 1, 3, 2], label="B")
    ax.set_title("Darkmode-compatible figure")
    ax.legend()

fig.savefig("figure.png", transparent=True)

References


https://matplotlib.org/stable/tutorials/advanced/patheffects_guide.html
https://matplotlib.org/stable/api/patheffects_api.html#matplotlib.patheffects.withStroke

좋은 웹페이지 즐겨찾기