2013-05-15 48 views
8

Tôi có một kịch bản matplotlib bắt đầu ...Cách tải tệp .ttf trong matplotlib bằng cách sử dụng mpl.rcParams?

import matplotlib as mpl 
import matplotlib.pyplot as plt 
import matplotlib.font_manager as fm 

mpl.rcParams['xtick.labelsize']=16 
... 

Tôi đã sử dụng lệnh

fm.findSystemFonts() 

để có được một danh sách các phông chữ trên hệ thống của tôi. Tôi đã phát hiện ra đường dẫn đầy đủ vào một tập tin .ttf Tôi muốn sử dụng,

'/usr/share/fonts/truetype/anonymous-pro/Anonymous Pro BI.ttf' 

Tôi đã cố gắng sử dụng phông chữ này nhưng không thành công bằng cách sử dụng lệnh sau

mpl.rcParams['font.family'] = 'anonymous-pro' 

mpl.rcParams['font.family'] = 'Anonymous Pro BI' 

mà cả hai quay trở lại một cái gì đó giống như

/usr/lib/pymodules/python2.7/matplotlib/font_manager.py:1218: UserWarning: findfont: Font family ['anonymous-pro'] not found. Falling back to Bitstream Vera Sans 

Tôi có thể sử dụng từ điển mpl.rcParams để đặt phông chữ này trong ô của tôi không?

EDIT

Sau khi đọc thêm một chút, có vẻ như đây là vấn đề chung về xác định tên họ phông chữ từ tệp .ttf. Đây có phải là dễ dàng để làm trong linux hoặc python?

Bên cạnh đó, tôi đã cố gắng thêm

mpl.use['agg'] 
mpl.rcParams['text.usetex'] = False 

mà không cần bất kỳ sự thành công

Trả lời

11

Chỉ định họ phông chữ:

Nếu tất cả các bạn biết là đường dẫn đến ttf, sau đó bạn có thể khám phá tên họ phông chữ bằng cách sử dụng phương thức get_name:

import matplotlib as mpl 
import matplotlib.pyplot as plt 
import matplotlib.font_manager as font_manager 

path = '/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS.ttf' 
prop = font_manager.FontProperties(fname=path) 
mpl.rcParams['font.family'] = prop.get_name() 
fig, ax = plt.subplots() 
ax.set_title('Text in a cool font', size=40) 
plt.show() 

Chỉ định phông chữ bằng đường dẫn:

import matplotlib.pyplot as plt 
import matplotlib.font_manager as font_manager 

path = '/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS.ttf' 
prop = font_manager.FontProperties(fname=path) 
fig, ax = plt.subplots() 
ax.set_title('Text in a cool font', fontproperties=prop, size=40) 
plt.show() 
+0

nhờ. Tôi thấy rằng giải pháp trong bài viết này [http://stackoverflow.com/questions/12790284/why-doesnt-matplotlib-use-the-ttf-font-that-i-provide?rq=1). Tuy nhiên, tôi muốn thay đổi phông chữ của tất cả văn bản trên cốt truyện mà không cập nhật từng lệnh tạo văn bản và/hoặc thêm lệnh để thay đổi văn bản của nhãn trục. Đó là lý do tại sao tôi muốn sử dụng mpl.rcParams nếu có thể. –

+0

thực hiện thủ thuật. cảm ơn! –

+0

Tuyệt. Cảm ơn các câu trả lời chi tiết. Giúp đỡ rất nhiều! –

3

Bạn có thể sử dụng lệnh myfile.ttf fc-truy vấn để kiểm tra thông tin siêu dữ liệu của một phông chữ theo hệ thống phông chữ Linux (fontconfig). Nó sẽ in bạn tên matplotlib sẽ chấp nhận. Tuy nhiên, việc tích hợp phông chữ matplotlib là khá một phần ngay bây giờ, do đó, tôi e rằng bạn hoàn toàn có thể gặp phải các lỗi và giới hạn không tồn tại cho cùng một phông chữ trong các ứng dụng Linux khác.

(trạng thái buồn này được ẩn bởi tất cả các tên phông chữ mã hóa cứng trong cấu hình mặc định matplotlib của, ngay sau khi bạn bắt đầu cố gắng thay đổi chúng, bạn đang ở trong đất nguy hiểm)

1

Whew tôi đã làm cho nó ở dưới 100 dòng, @nim này cũng giải thích chi tiết hơn mức độ nguy hiểm của nó, một số sửa đổi thay đổi hoàn toàn hành vi của thuộc tính phông chữ và kích thước phông chữ.

điều kiện tiên quyết: Matplotlib và thư mục phông chữ ở cùng một mức của tập lệnh chứa caltri phông chữ ttf.ttf

Nhưng đây là những gì tôi có cho bạn như một quả trứng Phục sinh:

import os 
import matplotlib 
import matplotlib.pyplot as plt 
import matplotlib.font_manager as fm 
from matplotlib import ft2font 
from matplotlib.font_manager import ttfFontProperty 

__font_dir__ = os.path.join(os.path.dirname(__file__),"font") 
fpath = os.path.join(__font_dir__,'calibri.ttf') 

font = ft2font.FT2Font(fpath) 
fprop = fm.FontProperties(fname=fpath) 

ttfFontProp = ttfFontProperty(font) 

fontsize=18 

fontprop = fm.FontProperties(family='sans-serif', 
          #name=ap.fontprop.name, 
          fname=ttfFontProp.fname, 
          size=fontsize, 
          stretch=ttfFontProp.stretch, 
          style=ttfFontProp.style, 
          variant=ttfFontProp.variant, 
          weight=ttfFontProp.weight) 

matplotlib.rcParams.update({'font.size': fontsize, 
         'font.family': 'sans-serif'}) 

fig, axis = plt.subplots() 

axis.set_title('Text in a cool font',fontsize=fontsize,fontproperties=fontprop) 

ax_right = axis.twinx() 

axis.set_xlabel("some Unit",fontsize=fontsize,fontproperties=fontprop) 

leftAxesName,rightAxesName = "left Unit", "right Unit" 

axis.set_ylabel(leftAxesName,fontsize=fontsize,fontproperties=fontprop) 
if rightAxesName: 
    ax_right.set_ylabel(rightAxesName,fontsize=fontsize,fontproperties=fontprop) 

for xLabel in axis.get_xticklabels(): 
    xLabel.set_fontproperties(fontprop) 
    xLabel.set_fontsize(fontsize) 

for yLabel in axis.get_yticklabels(): 
    yLabel.set_fontproperties(fontprop) 
    yLabel.set_fontsize(fontsize)  

yTickLabelLeft = ax_right.get_yticklabels() 

for yLabel in yTickLabelLeft: 
    yLabel.set_fontproperties(fontprop) 
    yLabel.set_fontsize(fontsize) 

axis.plot([0,1],[0,1],label="test") 

nrow,ncol=1,1 
handels,labels= axis.get_legend_handles_labels() 

propsLeft=axis.properties() 

propsRight=ax_right.properties() 

print(propsLeft['title'],propsLeft['xlabel'],propsLeft['ylabel']) 
print(propsRight['ylabel']) 

fig.set_tight_layout({'rect': [0, 0, 1, 0.95], 'pad': 0.05, 'h_pad': 1.5}) 
fig.tight_layout() 
fig.set_alpha(True) 

leg_fig = plt.figure() 

leg = leg_fig.legend(handels, labels, #labels = tuple(bar_names) 
    ncol=ncol, mode=None, 
    borderaxespad=0., 
    loc='center',  # the location of the legend handles 
    handleheight=None, # the height of the legend handles 
    #fontsize=9,   # prop beats fontsize 
    markerscale=None, 
    frameon=False, 
    prop=fontprop) 

plt.show() 
Các vấn đề liên quan