matplotlib同時顯示中文和特殊符號
一、總結
一句話總結:
直接分開寫,加號連接即可
plt.text(0.1,6,r'x均值'+r'$:\mu_x$', fontdict={'size':16,'color':'r'})
1、matplotlib中使用TeX標記?
你可以在任何 matplotlib 文本字符串中使用子 TeX 標記,【將它放在一對美元符號($)內】。
注意,你不需要安裝 TeX,因為【matplotlib 提供了自己的 TeX 表達式解析器,布局引擎和字體】 。
二、matplotlib同時顯示中文和特殊符號
import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import make_interp_spline # 設置matplotlib庫字體的非襯線字體為黑體 plt.rcParams["font.sans-serif"]=["SimHei"] # 設置matplotlib庫字體族為非襯線字體 plt.rcParams["font.family"]="sans-serif" fig, ax = plt.subplots() # 取消邊框 for key, spine in ax.spines.items(): # 'left', 'right', 'bottom', 'top' if key == 'left' or key == 'right': spine.set_visible(False) plt.xticks([]) plt.yticks([]) x=np.array([1,2,3,4,5]) y=np.array([4,9,6,8,3]) y_mean=np.mean(y).repeat(5) print(y_mean) #plt.plot(x,y,'ro') plt.plot(x,y,color='red', marker='o', linestyle='dashed',linewidth=0, markersize=12) plt.plot(x,y_mean,'k--') x_smooth = np.linspace(x.min(),x.max(),300) #300 represents number of points to make between T.min and T.max y_smooth = make_interp_spline(x, y)(x_smooth) plt.plot(x_smooth,y_smooth,'r--') plt.text(0.1,6,r'x均值'+r'$:\mu_x$', fontdict={'size':16,'color':'r'}) plt.show()
三、Python Matplotlib中坐標軸標題中各種特殊符號的顯示 轉義字符全集,編寫數學表達式
轉自或參考:Python Matplotlib中坐標軸標題中各種特殊符號的顯示 轉義字符全集,編寫數學表達式
https://blog.csdn.net/lqv587ss/article/details/84190528
Matplotlib中文顯示問題——用例子說明問題
#-*- coding: utf-8 -*-
from pylab import *
t = arange(-4*pi, 4*pi, 0.01)
y = sin(t)/t
plt.plot(t, y)
plt.title('test')
plt.xlabel(u'\u2103',fontproperties='SimHei')
#在這里,u'\u2103'是攝氏度,前面的u代表unicode,而引號里的內容,是通過在網上查找“℃”這一個符號的unicode編碼得到的。這里的“攝氏度”是中文,要顯示的話需要在后面加上fontproperties屬性即可,這里設置的字體為黑體。
plt.ylabel(u'幅度',fontproperties='SimHei')#也可以直接顯示中文。
plt.show()
可以這樣使用:ylabel('Rice('+r'$\mu\mathrm{mol}$'+' '+'$ \mathrm{m}^{-2} \mathrm{s}^{-1}$'+')')。
中文與LaTex共同顯示問題:
在坐標軸標題中同時顯示中文以及帶有上下標的各種數學單位,需要分兩步:
1、根據上述顯示中文的方法,先將中文標題加上;
2、對於單位,使用text函數進行添加,text函數用法見(http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.text)。
import matplotlib.pyplot as plt
import numpy as np
t = np.linspace(0, 10, 1000)
y = np.sin(t)
plt.plot(t, y,label=u'正弦曲線 (m)')
plt.xlabel(u"時間", fontproperties='SimHei')
plt.ylabel(u"振幅", fontproperties='SimHei')
plt.title(u"正弦波", fontproperties='SimHei'
# 添加單位
t=plt.text(6.25, -1.14,r'$(\mu\mathrm{mol}$'+' '+'$ \mathrm{m}^{-2} \mathrm{s}^{-1})$',fontsize=15, horizontalalignment='center',verticalalignment='center')
#在這里設置是text的旋轉,0為水平,90為豎直
t.set_rotation(0)
# legend中顯示中文
plt.legend(prop={'family':'SimHei','size':15})
plt.savefig("C:\\Users\\Administrator\\Desktop\\test.png")
編寫數學表達式
你可以在任何 matplotlib 文本字符串中使用子 TeX 標記,將它放在一對美元符號($
)內。
注意,你不需要安裝 TeX,因為 matplotlib 提供了自己的 TeX 表達式解析器,布局引擎和字體。 布局引擎是 Donald Knuth 的 TeX 中的布局算法的一種相當直接的適配版,所以質量是相當不錯的(matplotlib 還為那些想要調用 TeX 生成文本的人提供一個usetex
選項(參見使用 LaTeX 渲染文本 )。
任何文本元素都可以使用數學文本。 你應該使用原始字符串(在引號前面加一個'r'
),並用美元符號($
)包圍數學文本,如 TeX。 常規文本和數學文本可以在同一個字符串內交錯。 Mathtext 可以使用 Computer Modern 字體(來自 (La)TeX),STIX 字體(為與 Times 混合使用而設計)或你提供的 Unicode 字體。 可以使用自定義變量mathtext.fontset
選擇 mathtext 字體(請參閱自定義 matplotlib)
- 注意在Python的 『narrow』 構建中,如果使用 STIX 字體,你還應該將
ps.fonttype
和pdf.fonttype
設置為 3(默認值),而不是 42。否則一些字符將不可見。
下面是個簡單的例子:plt.title('alpha > beta'),生成alpha > beta;
但是這個: plt.title(r'$\alpha > \beta$'),會生成 。
-
注意:Mathtext 應該放在一對美元符號(
$
)之間。 為了易於顯示貨幣值,例如$ 100.00
,如果整個字符串中存在單個美元符號,則它將被逐字顯示為美元符號。 這是常規 TeX 的一個小改變,其中非數學文本中的美元符號必須被轉義('$'
)。 -
注意:雖然一對美元符號(
$
)內的語法是 TeX 風格的,但是外面的文本不是。 特別是,字符:# $ % & ~ _ ^ \ { } \( \) \[ \]
在 TeX 中的數學模式之外有特殊的意義。 因此,根據rcParam text.usetex
標志這些字符的表現有所不同。 更多信息請參閱usetex
教程。
下標和上標
為了制作下標和上標,使用_
或者^
符號: r'$\alpha_i > \beta_i$'
即為:
一些符號會自動將它們的下標或上標放在操作符的底部或頂部,例如,為了編寫 0 到無窮的 的和,你可以:
r'$\sum_{i=0}^\infty x_i$'
分數、二項式和堆疊數
可以使用\frac{}{}
,\binomial{}{}
和\stackrel{}{}
命令分別創建分數,二項式和堆疊數字:r'$\frac{3}{4} \binom{3}{4} \stackrel{3}{4}$'
產生
分數可以任意嵌套:r'$\frac{5 - \frac{1}{x}}{4}$'
產生
請注意,在分數周圍放置圓括號和花括號需要特別注意。 這種明顯的方式會產生太小的括號:
r'$(\frac{5 - \frac{1}{x}}{4})$'
解決方案是在括號前面加上\left
和\right
以通知解析器這些括號包含整個對象:r'$\left(\frac{5 - \frac{1}{x}}{4}\right)$'
根式
根式可以有\sqrt[]{}
產生,例如:r'$\sqrt{2}$'
方括號內可以(可選地)設置任何底數。 請注意,底數必須是一個簡單的表達式,並且不能包含布局命令,如分數或上下標:
r'$\sqrt[3]{x}$'
字體
用於數學符號的默認字體是斜體。
- 注意:此默認值可以使用
mathtext.default
rcParam
更改。 這是非常有用的,例如,通過將其設置為regular
,使用與常規非數學文本相同的字體作為數學文本。
為了修改字體,例如,以羅馬字體編寫sin
,使用字體命令來閉合文本:r'$s(t) = \mathcal{A}\mathrm{sin}(2 \omega t)$'
這里s
和t
是斜體(默認)的變量,sin
是羅馬字體,振幅A
是書法字體。 注意在上面的例子中,A
和sin
之間的間距被擠壓。 你可以使用間距命令在它們之間添加一些空格:s(t) = \mathcal{A}\/\sin(2 \omega t)
所有字體的可用選項為:
命令 | 結果 |
---|---|
\mathrm{Roman} |
![]() |
\mathit{Italic} |
![]() |
\mathtt{Typewriter} |
![]() |
\mathcal{CALLIGRAPHY} |
![]() |
使用 STIX 字體時,你也可以選擇:
命令 | 結果 |
---|---|
\mathbb{blackboard} |
![]() |
\mathrm{\mathbb{blackboard}} |
![]() |
\mathfrak{Fraktur} |
![]() |
\mathsf{sansserif} |
![]() |
\mathrm{\mathsf{sansserif}} |
![]() |
\mathcircled{circled} |
![]() |
還有三個全局『字體集』可供選擇,它們使用matplotlibrc
中的mathtext.fontset
參數進行選擇。
cm
: Computer Modern (TeX)
stix
: STIX (為和 Times 混合使用而設計)
stixsans
: STIX sans-serif
此外,你可以使用\mathdefault{...}
或其別名\mathregular{...}
來使用用於 mathtext 之外的常規文本的字體。 這種方法有一些限制,最明顯的是,可以使用很少的符號,但可用於將數學表達式與圖中的其他文本混合。
自定義字體
mathtext 還提供了一種對數學公式使用自定義字體的方法。 這種方法使用起來相當棘手,應該看做為有耐心的用戶准備的試驗特性。 通過將rcParam mathtext.fontset
設置為custom
,你可以設置以下參數,這些參數控制用於特定數學字符集的字體文件。
參數 | 相當於 |
---|---|
mathtext.it |
\mathit{} 默認斜體 |
mathtext.rm |
\mathrm{} 羅馬字體(upright) |
mathtext.tt |
\mathtt{} 打字機(monospace) |
mathtext.bf |
\mathbf{} 粗體 |
mathtext.cal |
\mathcal{} 書法 |
mathtext.sf |
\mathsf{} sans-serif |
每個參數應該設置為fontconfig
字體描述符(在尚未編寫的字體章節中定義)。
所使用的字體應該具有 Unicode 映射,以便找到任何非拉丁字符,例如希臘語。 如果要使用未包含在自定義字體中的數學符號,可以將rcParam mathtext.fallback_to_cm
設置為True
,這將導致自定義字體中找不到特定字符時,數學文本系統使用默認的 Computer Modern 字體中的字符。
請注意,Unicode 中規定的數學字形隨時間而演進,許多字體的字形對於 mathtext 可能不在正確位置。
重音符號
重音命令可以位於任何符號之前,在其上添加重音。 他們中的一些些擁有較長和較短的形式。
命令 | 結果 |
---|---|
\acute a 或 \'a |
![]() |
\bar a |
![]() |
\breve a |
![]() |
\ddot a 或 \"a |
![]() |
\dot a 或 \.a |
![]() |
\grave a 或 \ a` |
![]() |
\hat a 或 \^a |
![]() |
\tilde a 或 \~a |
![]() |
\vec a |
![]() |
\overline{abc} |
![]() |
另外有兩個特殊的重音符號,可以自動調整為符號的寬度:
命令 | 結果 |
---|---|
\widehat{xyz} |
![]() |
\widetilde{xyz} |
![]() |
當把重音放在小寫的i
和j
上時應該小心。 注意下面的\imath
用來避免i
上額外的點:r"$\hat i\ \ \hat \imath$"
符號
你也可以使用更大量的 TeX 符號,比如\infty
,\leftarrow
,\sum
,\int
。
小寫希臘字母 | ||
---|---|---|
![]() \alpha |
![]() \beta |
![]() \chi |
![]() \epsilon |
![]() \eta |
![]() \gamma |
![]() \lambda |
![]() \mu |
![]() \nu |
![]() \pi |
![]() \psi |
![]() \rho |
![]() \theta |
![]() \upsilon |
![]() \varepsilon |
![]() \varpi |
![]() \varrho |
![]() \varsigma |
![]() \zeta |
大寫希臘字母 | ||
---|---|---|
![]() \Delta |
![]() \Gamma |
![]() \Lambda |
![]() \Psi |
![]() \Sigma |
![]() \Theta |
![]() \nabla |
希伯來文 | ||
---|---|---|
![]() \aleph |
![]() \beth |
![]() \daleth |
分隔符 | ||
---|---|---|
![]() / |
![]() [ |
![]() \Downarrow |
![]() \downarrow |
![]() \langle |
![]() \lceil |
![]() \rangle |
![]() \rceil |
![]() \rfloor |
![]() \vert |
![]() \{ |
![]() | |
大型符號 | ||
---|---|---|
![]() \bigcap |
![]() \bigcup |
![]() \bigodot |
![]() \biguplus |
![]() \bigvee |
![]() \bigwedge |
![]() \oint |
![]() \prod |
![]() \sum |
標准函數名稱 | ||
---|---|---|
![]() \Pr |
![]() \arccos |
![]() \arcsin |
![]() \arg |
![]() \cos |
![]() \cosh |
![]() \coth |
![]() \csc |
![]() \deg |
![]() \dim |
![]() \exp |
![]() \gcd |
![]() \inf |
![]() \ker |
![]() \lg |
![]() \liminf |
![]() \limsup |
![]() \ln |
![]() \max |
![]() \min |
![]() \sec |
![]() \sinh |
![]() \sup |
![]() \tan |
二元運算符和關系符號 | ||
---|---|---|
![]() \Bumpeq |
![]() \Cap |
![]() \Cup |
![]() \Doteq |
![]() \Join |
![]() \Subset |
![]() \Supset |
![]() \Vdash |
![]() \Vvdash |
![]() \approx |
![]() \approxeq |
![]() \ast |
![]() \asymp |
![]() \backepsilon |
![]() \backsim |
![]() \backsimeq |
![]() \barwedge |
![]() \because |
![]() \between |
![]() \bigcirc |
![]() \bigtriangledown |
![]() \bigtriangleup |
![]() \blacktriangleleft |
![]() \blacktriangleright |
![]() \bot |
![]() \bowtie |
![]() \boxdot |
![]() \boxminus |
![]() \boxplus |
![]() \boxtimes |
![]() \bullet |
![]() \bumpeq |
![]() \cap |
![]() \cdot |
![]() \circ |
![]() \circeq |
![]() \coloneq |
![]() \cong |
![]() \cup |
![]() \curlyeqprec |
![]() \curlyeqsucc |
![]() \curlyvee |
![]() \curlywedge |
![]() \dag |
![]() \dashv |
![]() \ddag |
![]() \diamond |
![]() \div |
![]() \divideontimes |
![]() \doteq |
![]() \doteqdot |
![]() \dotplus |
![]() \doublebarwedge |
![]() \eqcirc |
![]() \eqcolon |
![]() \eqsim |
![]() \eqslantgtr |
![]() \eqslantless |
![]() \equiv |
![]() \fallingdotseq |
![]() \frown |
![]() \geq |
![]() \geqq |
![]() \geqslant |
![]() \gg |
![]() \ggg |
![]() \gnapprox |
![]() \gneqq |
![]() \gnsim |
![]() \gtrapprox |
![]() \gtrdot |
![]() \gtreqless |
![]() \gtreqqless |
![]() \gtrless |
![]() \gtrsim |
![]() \in |
![]() \intercal |
![]() \leftthreetimes |
![]() \leq |
![]() \leqq |
![]() \leqslant |
![]() \lessapprox |
![]() \lessdot |
![]() \lesseqgtr |
![]() \lesseqqgtr |
![]() \lessgtr |
![]() \lesssim |
![]() \ll |
![]() \lll |
![]() \lnapprox |
![]() \lneqq |
![]() \lnsim |
![]() \ltimes |
![]() \mid |
![]() \models |
![]() \mp |
![]() \nVDash |
![]() \nVdash |
![]() \napprox |
![]() \ncong |
![]() \ne |
![]() \neq |
![]() \neq |
![]() \nequiv |
![]() \ngeq |
![]() \ngtr |
![]() \ni |
![]() \nleq |
![]() \nless |
![]() \nmid |
![]() \notin |
![]() \nparallel |
![]() \nprec |
![]() \nsim |
![]() \nsubset |
![]() \nsubseteq |
![]() \nsucc |
![]() \nsupset |
![]() \nsupseteq |
![]() \ntriangleleft |
![]() \ntrianglelefteq |
![]() \ntriangleright |
![]() \ntrianglerighteq |
![]() \nvDash |
![]() \nvdash |
![]() \odot |
![]() \ominus |
![]() \oplus |
![]() \oslash |
![]() \otimes |
![]() \parallel |
![]() \perp |
![]() \pitchfork |
![]() \pm |
![]() \prec |
![]() \precapprox |
![]() \preccurlyeq |
![]() \preceq |
![]() \precnapprox |
![]() \precnsim |
![]() \precsim |
![]() \propto |
![]() \rightthreetimes |
![]() \risingdotseq |
![]() \rtimes |
![]() \sim |
![]() \simeq |
![]() \slash |
![]() \smile |
![]() \sqcap |
![]() \sqcup |
![]() \sqsubset |
![]() \sqsubset |
![]() \sqsubseteq |
![]() \sqsupset |
![]() \sqsupset |
![]() \sqsupseteq |
![]() \star |
![]() \subset |
![]() \subseteq |
![]() \subseteqq |
![]() \subsetneq |
![]() \subsetneqq |
![]() \succ |
![]() \succapprox |
![]() \succcurlyeq |
![]() \succeq |
![]() \succnapprox |
![]() \succnsim |
![]() \succsim |
![]() \supset |
![]() \supseteq |
![]() \supseteqq |
![]() \supsetneq |
![]() \supsetneqq |
![]() \therefore |
![]() \times |
![]() \top |
![]() \triangleleft |
![]() \trianglelefteq |
![]() \triangleq |
![]() \triangleright |
![]() \trianglerighteq |
![]() \uplus |
![]() \vDash |
![]() \varpropto |
![]() \vartriangleleft |
![]() \vartriangleright |
![]() \vdash |
![]() \vee |
![]() \veebar |
![]() \wedge |
![]() \wr |
箭頭符號 | 所有向上箭頭前面都要有兩個\ |
|
---|---|---|
![]() \Downarrow |
![]() \Leftarrow |
|
![]() \Leftrightarrow |
![]() \Lleftarrow |
|
![]() \Longleftarrow |
![]() \Longleftrightarrow |
|
![]() \Longrightarrow |
![]() \Lsh |
|
![]() \Nearrow |
![]() \Nwarrow |
|
![]() \Rightarrow |
![]() \Rrightarrow |
|
![]() \Rsh |
![]() \Searrow |
|
![]() \Swarrow |
![]() \Uparrow |
|
![]() \Updownarrow |
![]() \circlearrowleft |
|
![]() \circlearrowright |
![]() \curvearrowleft |
|
![]() \curvearrowright |
![]() \dashleftarrow |
|
![]() \dashrightarrow |
![]() \downarrow |
|
![]() \downdownarrows |
![]() \downharpoonleft |
|
![]() \downharpoonright |
![]() \hookleftarrow |
|
![]() \hookrightarrow |
![]() \leadsto |
|
![]() \leftarrow |
![]() \leftarrowtail |
|
![]() \leftharpoondown |
![]() \leftharpoonup |
|
![]() \leftleftarrows |
![]() \leftrightarrow |
|
![]() \leftrightarrows |
![]() \leftrightharpoons |
|
![]() \leftrightsquigarrow |
![]() \leftsquigarrow |
|
![]() \longleftarrow |
![]() \longleftrightarrow |
|
![]() \longmapsto |
![]() \longrightarrow |
|
![]() \looparrowleft |
![]() \looparrowright |
|
![]() \mapsto |
![]() \multimap |
|
![]() \nLeftarrow |
![]() \nLeftrightarrow |
|
![]() \nRightarrow |
![]() \nearrow |
|
![]() \nleftarrow |
![]() \nleftrightarrow |
|
![]() \nrightarrow |
![]() \nwarrow |
|
![]() \rightarrow |
![]() \rightarrowtail |
|
![]() \rightharpoondown |
![]() \rightharpoonup |
|
![]() \rightleftarrows |
![]() \rightleftarrows |
|
![]() \rightleftharpoons |
![]() \rightleftharpoons |
|
![]() \rightrightarrows |
![]() \rightrightarrows |
|
![]() \rightsquigarrow |
![]() \searrow |
|
![]() \swarrow |
![]() \to |
|
![]() \twoheadleftarrow |
![]() \twoheadrightarrow |
|
![]() \uparrow |
![]() \updownarrow |
|
![]() \updownarrow |
![]() \upharpoonleft |
|
![]() \upharpoonright |
![]() \upuparrows |
雜項符號 | ||
---|---|---|
![]() \$ |
![]() \AA |
![]() \Finv |
![]() \Game |
![]() \Im |
![]() \P |
![]() \Re |
![]() \S |
![]() \angle |
![]() \backprime |
![]() \bigstar |
![]() \blacksquare |
![]() \blacktriangle |
![]() \blacktriangledown |
![]() \cdots |
![]() \checkmark |
![]() \circledR |
![]() \circledS |
![]() \clubsuit |
![]() \complement |
![]() \copyright |
![]() \ddots |
![]() \diamondsuit |
![]() \ell |
![]() \emptyset |
![]() \eth |
![]() \exists |
![]() \flat |
![]() \forall |
![]() \hbar |
![]() \heartsuit |
![]() \hslash |
![]() \iiint |
![]() \iint |
![]() \iint |
![]() \imath |
![]() \infty |
![]() \jmath |
![]() \ldots |
![]() \measuredangle |
![]() \natural |
![]() \neg |
![]() \nexists |
![]() \oiiint |
![]() \partial |
![]() \prime |
![]() \sharp |
![]() \spadesuit |
![]() \sphericalangle |
![]() \ss |
![]() \triangledown |
![]() \varnothing |
![]() \vartriangle |
![]() \vdots |
![]() \wp |
![]() \yen |
如果特定符號沒有名稱(對於 STIX 字體中的許多較為模糊的符號也是如此),也可以使用 Unicode 字符:ur'$\u23ce$'
示例
下面是個示例,在上下文中展示了許多這些特性。
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)
plt.plot(t,s)
plt.title(r'$\alpha_i > \beta_i$', fontsize=20)
plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)
plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$',fontsize=20)
plt.xlabel('time (s)')
plt.ylabel('volts (mV)')
plt.show()