matplotlib text 加入分段函數(shù)的公式

百度查了半天沒有找到,
Google上查到有人解決了這個(gè)問題:

#/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()
image.png

參考這里https://stackoverflow.com/questions/21392152/how-can-i-write-a-piecewise-function-latex-code-in-matplotlib

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容