matplotlib 그림의 글꼴 크기를 변경하는 방법
matplotlib 그림의 모든 요소(틱, 레이블, 제목)에 대한 글꼴 크기를 변경하려면 어떻게 해야 합니까?
눈금 레이블 크기를 변경하는 방법을 알고 있습니다. 이 작업은 다음과 같이 수행됩니다.
import matplotlib
matplotlib.rc('xtick', labelsize=20)
matplotlib.rc('ytick', labelsize=20)
하지만 어떻게 나머지를 바꿀 수 있을까요?
font = {'family' : 'normal',
'weight' : 'bold',
'size' : 22}
matplotlib.rc('font', **font)
모든 오브젝트인 kwargs에서 됩니다.font
.
외에 '먹다'를 할 수도 있습니다.rcParams
update
다음 답변에 제시된 방법:
matplotlib.rcParams.update({'font.size': 22})
또는
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 22})
사용 가능한 속성의 전체 목록은 matplotlib 사용자 지정 페이지에서 확인할 수 있습니다.
저와 같은 제어광이라면 모든 글꼴 크기를 명시적으로 설정할 수 있습니다.
import matplotlib.pyplot as plt
SMALL_SIZE = 8
MEDIUM_SIZE = 10
BIGGER_SIZE = 12
plt.rc('font', size=SMALL_SIZE) # controls default text sizes
plt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title
.rc
의 메서드입니다.matplotlib
:
import matplotlib
SMALL_SIZE = 8
matplotlib.rc('font', size=SMALL_SIZE)
matplotlib.rc('axes', titlesize=SMALL_SIZE)
# and so on ...
이미 작성된 특정 플롯의 글꼴 크기만 변경하려면 다음을 수행하십시오.
import matplotlib.pyplot as plt
ax = plt.subplot(111, xlabel='x', ylabel='y', title='title')
for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
ax.get_xticklabels() + ax.get_yticklabels()):
item.set_fontsize(20)
matplotlib.rcParams.update({'font.size': 22})
업데이트: 조금 더 나은 방법은 답변 하단을 참조하십시오.
업데이트 2: 범례 제목 글꼴도 변경했습니다.
업데이트 3:Matplotlib 2.0.0에는 로그 축의 눈금 레이블을 기본 글꼴로 되돌리는 버그가 있습니다.2.0.1에서 수정되어야 하지만 답변의 두 번째 부분에 회피책을 포함시켰습니다.
이 답변은 범례를 포함하여 모든 글꼴을 변경하려는 사용자 및 각 항목에 대해 다른 글꼴과 크기를 사용하려는 사용자를 위한 것입니다.rc를 사용하지 않습니다(저에게는 효과가 없는 것 같습니다).다소 번거롭지만 개인적으로 다른 방법을 강구할 수 없었습니다.기본적으로 여기 Ryggyr의 답변과 SO에 대한 다른 답변이 결합되어 있습니다.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
# Set the font dictionaries (for plot title and axis titles)
title_font = {'fontname':'Arial', 'size':'16', 'color':'black', 'weight':'normal',
'verticalalignment':'bottom'} # Bottom vertical alignment for more space
axis_font = {'fontname':'Arial', 'size':'14'}
# Set the font properties (for use in legend)
font_path = 'C:\Windows\Fonts\Arial.ttf'
font_prop = font_manager.FontProperties(fname=font_path, size=14)
ax = plt.subplot() # Defines ax variable by creating an empty plot
# Set the tick labels font
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
label.set_fontname('Arial')
label.set_fontsize(13)
x = np.linspace(0, 10)
y = x + np.random.normal(x) # Just simulates some data
plt.plot(x, y, 'b+', label='Data points')
plt.xlabel("x axis", **axis_font)
plt.ylabel("y axis", **axis_font)
plt.title("Misc graph", **title_font)
plt.legend(loc='lower right', prop=font_prop, numpoints=1)
plt.text(0, 0, "Misc text", **title_font)
plt.show()
이 방법의 장점은 여러 글꼴 사전을 보유함으로써 다양한 제목에 대해 서로 다른 글꼴/사이즈/무게/컬러를 선택하고 눈금 레이블의 글꼴 및 범례의 글꼴을 모두 독립적으로 선택할 수 있다는 것입니다.
갱신:
글꼴 사전을 없애고 시스템상의 글꼴, 심지어 .otf 글꼴을 사용할 수 있는 조금 다른, 덜 번잡한 접근 방식을 고안했습니다.를 더 font_path
★★★★★★★★★★★★★★★★★」font_prop
수와같같 같같같다다
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
import matplotlib.ticker
# Workaround for Matplotlib 2.0.0 log axes bug https://github.com/matplotlib/matplotlib/issues/8017 :
matplotlib.ticker._mathdefault = lambda x: '\\mathdefault{%s}'%x
# Set the font properties (can use more variables for more fonts)
font_path = 'C:\Windows\Fonts\AGaramondPro-Regular.otf'
font_prop = font_manager.FontProperties(fname=font_path, size=14)
ax = plt.subplot() # Defines ax variable by creating an empty plot
# Define the data to be plotted
x = np.linspace(0, 10)
y = x + np.random.normal(x)
plt.plot(x, y, 'b+', label='Data points')
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
label.set_fontproperties(font_prop)
label.set_fontsize(13) # Size here overrides font_prop
plt.title("Exponentially decaying oscillations", fontproperties=font_prop,
size=16, verticalalignment='bottom') # Size here overrides font_prop
plt.xlabel("Time", fontproperties=font_prop)
plt.ylabel("Amplitude", fontproperties=font_prop)
plt.text(0, 0, "Misc text", fontproperties=font_prop)
lgd = plt.legend(loc='lower right', prop=font_prop) # NB different 'prop' argument for legend
lgd.set_title("Legend", prop=font_prop)
plt.show()
이것이 포괄적인 답변이기를 바랍니다.
글꼴 크기를 변경하는 데 놀라울 정도로 효과적인 완전히 다른 방법을 소개합니다.
피규어 사이즈 변경!
저는 보통 다음과 같은 코드를 사용합니다.
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
x = np.linspace(0,6.28,21)
ax.plot(x, np.sin(x), '-^', label="1 Hz")
ax.set_title("Oscillator Output")
ax.set_xlabel("Time (s)")
ax.set_ylabel("Output (V)")
ax.grid(True)
ax.legend(loc=1)
fig.savefig('Basic.png', dpi=300)
그림 크기를 작게 할수록 그림에 비해 글꼴이 커집니다.또한 마커를 업스케일링합니다.주의: 또,dpi
또는 인치당 도트(dot per inch.저는 이것을 AMTA(American Modeling Teacher of America) 포럼의 게시물에서 배웠습니다.위의 코드 예:
하시면 됩니다.plt.rcParams["font.size"]
font_size
matplotlib
,을 할 수 .plt.rcParams["font.family"]
font_family
matplotlib
를 들어 하다
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
label = [1,2,3,4,5,6,7,8]
x = [0.001906,0.000571308,0.0020305,0.0037422,0.0047095,0.000846667,0.000819,0.000907]
y = [0.2943301,0.047778308,0.048003167,0.1770876,0.532489833,0.024611333,0.157498667,0.0272095]
plt.ylabel('eigen centrality')
plt.xlabel('betweenness centrality')
plt.text(0.001906, 0.2943301, '1 ', ha='right', va='center')
plt.text(0.000571308, 0.047778308, '2 ', ha='right', va='center')
plt.text(0.0020305, 0.048003167, '3 ', ha='right', va='center')
plt.text(0.0037422, 0.1770876, '4 ', ha='right', va='center')
plt.text(0.0047095, 0.532489833, '5 ', ha='right', va='center')
plt.text(0.000846667, 0.024611333, '6 ', ha='right', va='center')
plt.text(0.000819, 0.157498667, '7 ', ha='right', va='center')
plt.text(0.000907, 0.0272095, '8 ', ha='right', va='center')
plt.rcParams["font.family"] = "Times New Roman"
plt.rcParams["font.size"] = "50"
plt.plot(x, y, 'o', color='blue')
plt.tick_params(labelsize=14)
Jupyter Notebook에서 일반적으로 사용하는 것은 다음과 같습니다.
# Jupyter Notebook settings
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:95% !important; }</style>"))
%autosave 0
%matplotlib inline
%load_ext autoreload
%autoreload 2
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
# Imports for data analysis
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option('display.max_rows', 2500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.max_colwidth', 2000)
pd.set_option('display.width', 2000)
pd.set_option('display.float_format', lambda x: '%.3f' % x)
#size=25
size=15
params = {'legend.fontsize': 'large',
'figure.figsize': (20,8),
'axes.labelsize': size,
'axes.titlesize': size,
'xtick.labelsize': size*0.75,
'ytick.labelsize': size*0.75,
'axes.titlepad': 25}
plt.rcParams.update(params)
「 」의 .rcParams
매우 세밀합니다.대부분의 경우, 모든 폰트 사이즈를 확대해, 그림으로 보기 좋게 하는 것만으로 충분합니다.피규어 사이즈는 좋은 요령이지만 모든 피규어에 대해 피규어를 휴대해야 합니다.다른 matplotlib이, seaborn을 않는 은입니다.
sns.set_context('paper', font_scale=1.4)
면책사항: 알고 있습니다. 만약 당신이 matplotlib만을 사용한다면, 당신은 플롯의 축척만을 위해 전체 모듈을 설치하고 싶지 않을 것입니다(내 말은 그렇지 않을 것입니다). 또는 seaborn을 사용한다면, 당신은 옵션을 더 많이 제어할 수 있습니다.그러나 데이터 사이언스 가상 환경에는 시본이 있지만 이 노트북에서는 사용하지 않는 경우가 있습니다.어쨌든, 또 다른 해결책이 있습니다.
위의 내용을 바탕으로 합니다.
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
fontPath = "/usr/share/fonts/abc.ttf"
font = fm.FontProperties(fname=fontPath, size=10)
font2 = fm.FontProperties(fname=fontPath, size=24)
fig = plt.figure(figsize=(32, 24))
fig.text(0.5, 0.93, "This is my Title", horizontalalignment='center', fontproperties=font2)
plot = fig.add_subplot(1, 1, 1)
plot.xaxis.get_label().set_fontproperties(font)
plot.yaxis.get_label().set_fontproperties(font)
plot.legend(loc='upper right', prop=font)
for label in (plot.get_xticklabels() + plot.get_yticklabels()):
label.set_fontproperties(font)
디폴트 폰트를 유지할 수 있도록 그림의 크기를 변경하는 것이 가장 간단한 방법이라는 Huster 교수의 의견에 전적으로 동의합니다.축 라벨이 잘려서 그림을 PDF로 저장할 때 bbox_inches 옵션으로 보완해야 했습니다.
import matplotlib.pyplot as plt
plt.figure(figsize=(4,3))
plt.savefig('Basic.pdf', bbox_inches='tight')
이것은 Marius Retegan의 답변의 확장입니다.모든 수정 사항을 포함하여 별도의 JSON 파일을 만들고 rcParams.update로 로드할 수 있습니다.변경 내용은 현재 스크립트에만 적용됩니다.그렇게
import json
from matplotlib import pyplot as plt, rcParams
s = json.load(open("example_file.json")
rcParams.update(s)
이 'file_file.json'을 같은 폴더에 저장합니다.
{
"lines.linewidth": 2.0,
"axes.edgecolor": "#bcbcbc",
"patch.linewidth": 0.5,
"legend.fancybox": true,
"axes.color_cycle": [
"#348ABD",
"#A60628",
"#7A68A6",
"#467821",
"#CF4457",
"#188487",
"#E24A33"
],
"axes.facecolor": "#eeeeee",
"axes.labelsize": "large",
"axes.grid": true,
"patch.edgecolor": "#eeeeee",
"axes.titlesize": "x-large",
"svg.fonttype": "path",
"examples.directory": ""
}
Herman Schaaf와 Pedro M Duarte의 답변이 모두 효과가 있다는 것을 지적하고 싶었을 뿐이지만, 당신은 그것을 인스턴스화하기 전에 해야 합니다.subplots()
이러한 설정은 이미 인스턴스화된 오브젝트에는 영향을 주지 않습니다.그것이 현명하지 않다는 것은 알지만, 서브플롯()을 호출한 후 이러한 변경 사항을 사용하려고 할 때, 왜 이러한 답변이 나에게 효과가 없는지 깨닫는 데 많은 시간을 할애했습니다.
예:
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 6,})
fig, ax = plt.subplots()
#create your plot
plt.show()
또는
SMALL_SIZE = 8
MEDIUM_SIZE = 10
BIGGER_SIZE = 12
plt.rc('font', size=SMALL_SIZE) # controls default text sizes
plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels
fig, ax = plt.subplots()
#create your plot
plt.show()
코멘트에 기재되어 있습니다만, 다음과 같이 대답할 가치가 있습니다.
둘 다 수정 figsize=
그리고.dpi=
를 사용하여 모든 텍스트 라벨의 그림 크기와 축척을 조정합니다.
fig, ax = plt.subplots(1, 1, figsize=(8, 4), dpi=100)
(또는 더 짧음:)
fig, ax = plt.subplots(figsize=(8, 4), dpi=100)
조금 까다롭습니다.
figsize
는 실제로 플롯 범위(및 플롯의 종횡비)에 상대적인 텍스트의 축척을 제어합니다.dpi
노트북 내 그림의 크기를 조정합니다(텍스트의 상대 축척과 플롯 애스펙트 비율을 일정하게 유지).
@ryggyr에 의한 답변의 수정 버전을 작성했습니다.개개의 파라미터를 보다 상세하게 제어할 수 있어 복수의 서브플롯에서 동작합니다.
def set_fontsizes(axes,size,title=np.nan,xlabel=np.nan,ylabel=np.nan,xticks=np.nan,yticks=np.nan):
if type(axes) != 'numpy.ndarray':
axes=np.array([axes])
options = [title,xlabel,ylabel,xticks,yticks]
for i in range(len(options)):
if np.isnan(options[i]):
options[i]=size
title,xlabel,ylabel,xticks,yticks=options
for ax in axes.flatten():
ax.title.set_fontsize(title)
ax.xaxis.label.set_size(xlabel)
ax.yaxis.label.set_size(ylabel)
ax.tick_params(axis='x', labelsize=xticks)
ax.tick_params(axis='y', labelsize=yticks)
언급URL : https://stackoverflow.com/questions/3899980/how-to-change-the-font-size-on-a-matplotlib-plot
'it-source' 카테고리의 다른 글
목록 목록에 있는 모든 문자열을 정수로 변환하려면 어떻게 해야 합니까? (0) | 2022.12.29 |
---|---|
Larabel 4: 웅변적인 ORM을 사용하여 '주문'하는 방법 (0) | 2022.12.29 |
JAXBelement 객체를 인스턴스화하려면 어떻게 해야 하나요? (0) | 2022.12.29 |
getc() vs fgetc() - 주요 차이점은 무엇입니까? (0) | 2022.12.29 |
C/C++ bool 타입은 type cast'에서 int로 설정했을 때 항상 0 또는 1로 보증됩니까? (0) | 2022.12.29 |