2014-01-27 76 views
1

我想在matplotlib分段表達這樣的傳奇節寫:如何在Matplotlib中編寫分段函數乳膠代碼?

\[f(x) = \left\{ 
    \begin{array}{lr} 
    x^2 & : x < 0\\ 
    x^3 & : x \ge 0 
    \end{array} 
\right. 
\] 

問題是Matplotlib不承認\開始\結束\等等。 謝謝

+0

這可能是除了'mathtex'的基本實現之外,您將不得不將工作導出爲完整的'LaTeX'。看看'usetex' rcparam。關閉我的頭頂,添加'text.usetex = True'到你的rcparam文件應該可以工作。 – tacaswell

+0

它不起作用,因爲在乳膠模式下不接受空格或換行符號,如\;或\\ – Tobal

+0

@tcaswell這確實是有效的LaTeX。在'\ left'和'\ right'之間有'數組'環境,這意味着'\ left'和'\ right'命令之間沒有換行符。這在LaTeX中排版簡單的條件函數並不罕見。 – hooy

回答

3

好的,這裏是解決方案。它包括加載乳膠mathsymbols包。它假設你已經在PC中安裝了所需的乳膠包。在​​

代碼的更多信息:

#/usr/bin/env python3 
# -*- coding: utf-8 -*- 


import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib import rcParams 


rcParams['text.latex.unicode'] = True 
rcParams['text.usetex'] = True 
rcParams['text.latex.preamble'] = '\usepackage{amsthm}', '\usepackage{amsmath}', '\usepackage{amssymb}', 
'\usepackage{amsfonts}', '\usepackage[T1]{fontenc}', '\usepackage[utf8]{inputenc}, \usepackage{multicol}' 
rcParams['legend.handleheight'] = 3.0 
#This fixes the legend line be placed at same height that text legend 


def f(x): 
    return np.piecewise(x, [x < 2.0, x > 2.0], [lambda x: x ** 2.0, lambda x: 4.0]) 


fig, ax = plt.subplots() 
x = np.linspace(-5.0, 5.0, 1000) 
ax.axis([x[0], x[-1], x[0], x[-1]]) 
ax.spines['left'].set_position('center') 
ax.spines['right'].set_color('none') 
ax.spines['bottom'].set_position('center') 
ax.spines['top'].set_color('none') 
ax.spines['left'] 
ax.spines['bottom'] 
ax.xaxis.set_ticks_position('bottom') 
ax.yaxis.set_ticks_position('left') 
ticks = [] 
for i in range(int(x[0]), int(x[-1] + 1), 1): 
    ticks.append(i) 
ticks.remove(0) 
ax.set_xticks(ticks) 
ax.set_yticks(ticks) 
ax.plot(x, f(x), 'b-', 2, 4, 'wo', markeredgecolor='b', 
     markerfacecolor='w', lw=2.0) 
tlegend = r'$f(x)=\left\{\begin{array}{lr} x^2 & : x<2\\ 4 & : x>2\end{array}\right\}$' 
ax.legend([tlegend], loc='lower right') 
ax.set_title(ur'$Función\; A\; Trozos$') # If you use accents put ur option. 
ax.grid('on') 
plt.show() 

圖像:

Solution 如果有人知道如何改進下面的代碼將受到歡迎:

rcParams['legend.handleheight'] = 3.0 
#This fixes the legend line be placed at same height that text legend