Hướng dẫn how to change font size python matplotlib - cách thay đổi kích thước phông chữ python matplotlib

CẬP NHẬT: Xem phần dưới của câu trả lời để biết cách thực hiện tốt hơn một chút. Các trục logarit để trở lại phông chữ mặc định. Nên được sửa trong 2.0.1 nhưng tôi đã bao gồm cách giải quyết trong phần thứ 2 của câu trả lời. See the bottom of the answer for a slightly better way of doing it.
Update #2: I've figured out changing legend title fonts too.
Update #3: There is a bug in Matplotlib 2.0.0 that's causing tick labels for logarithmic axes to revert to the default font. Should be fixed in 2.0.1 but I've included the workaround in the 2nd part of the answer.

Câu trả lời này dành cho bất kỳ ai cố gắng thay đổi tất cả các phông chữ, bao gồm cả truyền thuyết và cho bất kỳ ai cố gắng sử dụng các phông chữ và kích cỡ khác nhau cho mỗi thứ. Nó không sử dụng RC (dường như không hiệu quả với tôi). Nó khá cồng kềnh nhưng tôi không thể nắm bắt được bất kỳ phương pháp nào khác. Về cơ bản, nó kết hợp câu trả lời của Ryggyr ở đây với các câu trả lời khác về 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()

Lợi ích của phương pháp này là, bằng cách có một số từ điển phông chữ, bạn có thể chọn các phông chữ/kích thước/trọng lượng/màu khác nhau cho các tiêu đề khác nhau, chọn phông chữ cho nhãn đánh dấu và chọn phông chữ cho truyền thuyết, tất cả đều độc lập.


UPDATE:

Tôi đã thực hiện một cách tiếp cận hơi khác biệt, ít lộn xộn hơn, loại bỏ từ điển phông chữ và cho phép bất kỳ phông chữ nào trên hệ thống của bạn, thậm chí là phông chữ .OTF. Để có các phông chữ riêng cho mỗi thứ, chỉ cần viết thêm font_pathfont_prop như các biến.

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()

Hy vọng rằng đây là một câu trả lời toàn diện

Giới thiệu

Matplotlib là một trong những thư viện trực quan hóa dữ liệu được sử dụng rộng rãi nhất trong Python. Phần lớn sự phổ biến của Matplotlib đến từ các tùy chọn tùy chỉnh của nó - bạn có thể điều chỉnh bất kỳ yếu tố nào từ hệ thống phân cấp đối tượng của nó.

Trong hướng dẫn này, chúng ta sẽ xem xét cách thay đổi kích thước phông chữ trong matplotlib.

Thay đổi kích thước phông chữ trong matplotlib

Có một vài cách bạn có thể đi về việc thay đổi kích thước của phông chữ trong matplotlib. Bạn có thể đặt đối số fontsize, thay đổi cách matplotlib xử lý các phông chữ nói chung hoặc thậm chí thay đổi kích thước hình.

Trước tiên hãy tạo một cốt truyện đơn giản mà chúng ta sẽ muốn thay đổi kích thước của phông chữ trên:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(12, 6))

x = np.arange(0, 10, 0.1)
y = np.sin(x)
z = np.cos(x)

ax.plot(y, color='blue', label='Sine wave')
ax.plot(z, color='black', label='Cosine wave')
ax.set_title('Sine and cosine waves')
ax.set_xlabel('Time')
ax.set_ylabel('Intensity')
leg = ax.legend()

plt.show()

Thay đổi kích thước phông chữ bằng phông chữ

Hãy thử tùy chọn đơn giản nhất. Mỗi chức năng liên quan đến văn bản, chẳng hạn như

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()
0, nhãn và tất cả các hàm văn bản khác chấp nhận một đối số - fontsize.

Hãy xem lại mã từ trước và chỉ định fontsize cho các yếu tố này:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(12, 6))

x = np.arange(0, 10, 0.1)
y = np.sin(x)
z = np.cos(x)

ax.plot(y, color='blue', label='Sine wave')
ax.plot(z, color='black', label='Cosine wave')
ax.set_title('Sine and cosine waves', fontsize=20)
ax.set_xlabel('Time', fontsize=16)
ax.set_ylabel('Intensity', fontsize=16)
leg = ax.legend()

plt.show()

Ở đây, chúng tôi đã đặt fontsize cho tiêu đề cũng như các nhãn cho thời gian và cường độ. Chạy mã này mang lại:

Chúng ta cũng có thể thay đổi kích thước của phông chữ trong truyền thuyết bằng cách thêm đối số

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()
4 và đặt kích thước phông chữ ở đó:

leg = ax.legend(prop={"size":16})

Điều này sẽ thay đổi kích thước phông chữ, trong trường hợp này cũng di chuyển huyền thoại sang phía dưới bên trái để nó không trùng với các phần tử ở phía trên bên phải:

Tuy nhiên, trong khi chúng ta có thể đặt từng kích thước phông chữ như thế này, nếu chúng ta có nhiều yếu tố văn bản, và chỉ muốn một kích thước chung, đồng nhất - cách tiếp cận này là lặp đi lặp lại.

Trong những trường hợp như vậy, chúng ta có thể chuyển sang thiết lập kích thước phông chữ trên toàn cầu.

Thay đổi kích thước phông chữ trên toàn cầu

Có hai cách chúng ta có thể đặt kích thước phông chữ trên toàn cầu. Chúng tôi sẽ muốn đặt tham số

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()
5 thành một kích thước mới. Chúng ta có thể truy cập tham số này thông qua
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()
6.

Một cách là sửa đổi chúng trực tiếp:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(12, 6))

x = np.arange(0, 10, 0.1)
y = np.sin(x)
z = np.cos(x)

plt.rcParams['font.size'] = '16'

ax.plot(y, color='blue', label='Sine wave')
ax.plot(z, color='black', label='Cosine wave')
plt.xlabel('Time')
plt.ylabel('Intensity')
fig.suptitle('Sine and cosine waves')
leg = ax.legend()

plt.show()

Bạn phải đặt những thứ này trước khi gọi chức năng

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()
7 vì nếu bạn cố gắng áp dụng chúng sau đó, sẽ không có thay đổi nào được thực hiện. Cách tiếp cận này sẽ thay đổi mọi thứ được chỉ định là phông chữ của đối tượng
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()
8 KWARGS.

Tuy nhiên, khi chúng tôi chạy mã này, rõ ràng là X và Y sẽ đánh dấu, cũng như các nhãn X và Y không thay đổi về kích thước:

Kiểm tra hướng dẫn thực hành của chúng tôi, thực tế để học Git, với các thực hành tốt nhất, các tiêu chuẩn được công nghiệp chấp nhận và bao gồm bảng gian lận. Ngừng các lệnh git googling và thực sự tìm hiểu nó!

Tùy thuộc vào phiên bản matplotlib mà bạn đang chạy, bạn sẽ không thể thay đổi chúng bằng các tham số RC. Bạn sẽ sử dụng

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()
9 và ________ 20/________ 21 cho chúng tương ứng.

Nếu cài đặt những thứ này không thay đổi kích thước của nhãn, bạn có thể sử dụng hàm

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(12, 6))

x = np.arange(0, 10, 0.1)
y = np.sin(x)
z = np.cos(x)

ax.plot(y, color='blue', label='Sine wave')
ax.plot(z, color='black', label='Cosine wave')
ax.set_title('Sine and cosine waves')
ax.set_xlabel('Time')
ax.set_ylabel('Intensity')
leg = ax.legend()

plt.show()
2 được chuyển trong fontsize hoặc sử dụng hàm
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(12, 6))

x = np.arange(0, 10, 0.1)
y = np.sin(x)
z = np.cos(x)

ax.plot(y, color='blue', label='Sine wave')
ax.plot(z, color='black', label='Cosine wave')
ax.set_title('Sine and cosine waves')
ax.set_xlabel('Time')
ax.set_ylabel('Intensity')
leg = ax.legend()

plt.show()
4:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(12, 6))

x = np.arange(0, 10, 0.1)
y = np.sin(x)
z = np.cos(x)

# Set general font size
plt.rcParams['font.size'] = '16'

# Set tick font size
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
	label.set_fontsize(16)
	
ax.plot(y, color='blue', label='Sine wave')
ax.plot(z, color='black', label='Cosine wave')
plt.xlabel('Time', fontsize=16)
plt.ylabel('Intensity', fontsize=16)

fig.suptitle('Sine and cosine waves')
leg = ax.legend()

plt.show()

Kết quả này trong:

Sự kết luận

Trong hướng dẫn này, chúng tôi đã đi qua một số cách để thay đổi kích thước của phông chữ trong matplotlib.

Nếu bạn quan tâm đến trực quan hóa dữ liệu và không biết bắt đầu từ đâu, hãy đảm bảo kiểm tra gói sách của chúng tôi về trực quan hóa dữ liệu trong Python:

Trực quan hóa dữ liệu trong Python với matplotlib và pandas là một cuốn sách được thiết kế để đưa những người mới bắt đầu tuyệt đối đến gấu trúc và matplotlib, với kiến ​​thức python cơ bản và cho phép họ xây dựng một nền tảng mạnh mẽ cho các thư viện với các thư viện đơn giản đến nút. is a book designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and allow them to build a strong foundation for advanced work with theses libraries - from simple plots to animated 3D plots with interactive buttons.

Nó phục vụ như một hướng dẫn chuyên sâu, sẽ dạy cho bạn mọi thứ bạn cần biết về gấu trúc và matplotlib, bao gồm cách xây dựng các loại cốt truyện không được tích hợp vào thư viện.

Trực quan hóa dữ liệu trong Python, một cuốn sách dành cho người mới bắt đầu đến các nhà phát triển Python trung gian, hướng dẫn bạn thông qua thao tác dữ liệu đơn giản với gấu trúc, bao gồm các thư viện âm mưu cốt lõi như Matplotlib và Seaborn, và chỉ cho bạn cách tận dụng các thư viện khai báo và thử nghiệm như Altair. Cụ thể hơn, trong khoảng 11 chương, cuốn sách này bao gồm 9 thư viện Python: gấu trúc, matplotlib, Seaborn, Bokeh, Altair, Plotly, Ggplot, Geopandas và Vispy., a book for beginner to intermediate Python developers, guides you through simple data manipulation with Pandas, cover core plotting libraries like Matplotlib and Seaborn, and show you how to take advantage of declarative and experimental libraries like Altair. More specifically, over the span of 11 chapters this book covers 9 Python libraries: Pandas, Matplotlib, Seaborn, Bokeh, Altair, Plotly, GGPlot, GeoPandas, and VisPy.

Nó phục vụ như một hướng dẫn thực tế, độc đáo về trực quan hóa dữ liệu, trong rất nhiều công cụ bạn có thể sử dụng trong sự nghiệp của mình.

Bạn có thể thay đổi kích thước phông chữ trong matplotlib không?

Bạn có thể đặt đối số kích thước phông chữ, hình thay đổi cách matplotlib xử lý phông chữ nói chung hoặc thậm chí thay đổi kích thước hình., figsize change how Matplotlib treats fonts in general, or even change the figure size.

Kích thước phông chữ mặc định matplotlib là gì?

Lưu ý: Kích thước phông chữ mặc định cho tất cả các yếu tố là 10.10.