[英]Adding input variables to plot title/legend in Python
我想在 plot title/legend/annotated 文本中顯示用於 plot 某個 function 的參數的當前值。 舉個簡單的例子,我們取一條直線:
import numpy
import matplotlib.pyplot as plt
def line(m,c):
x = numpy.linspace(0,1)
y = m*x+c
plt.plot(x,y)
plt.text(0.1, 2.8, "The gradient is" *the current m-value should go here*)
plt.show()
print line(1.0, 2.0)
在這種情況下,我希望我的文本顯示“梯度為 1.0”,但我不確定語法是什么。 此外,我將如何在下面包含第二個(和更多)參數,以便它讀取:
“梯度為 1.0
截距為 2.0。”
使用.format()
方法的字符串格式:
plt.text(0.1, 2.8, "The gradient is {}, the intercept is {}".format(m, c))
其中m
和c
是您要替換的變量。
如果你在字符串前面添加一個f
whcih表示格式化的字符串文字,你可以直接在Python 3.6+中編寫這樣的變量:
f"the gradient is {m}, the intercept is {c}"
在python 3.6+中,您可以通過在字符串前加上f
,並將變量放在大括號中來實現。 對於早期的python版本,有各種方法,查找字符串格式
message = f"The slope is {m}"
plt.text(message)
(順便說一下,當提到單變量線性方程時, 梯度通常稱為斜率 )
其他答案對我的代碼不起作用,但對其進行了改編。 如下所示:
顯示 y = m*x + c 以日志格式打印在 plot 上。
a1 = coefs[0] # variable 1
a2 = coefs[1] # variable 2
message = f"log(L/Lo) = {a1} * log(M/Mo) + {a2}"
# Define axes
left = 0.01
width = 0.9
bottom = 0.01
height = 0.9
right = left + width
top = bottom + height
ax = plt.gca()
# Transform axes
ax.set_transform(ax.transAxes)
# Define text
ax.text(0.5 * (left + right), 0.5 * (bottom + top), message,
horizontalalignment='center',
verticalalignment='center',
size= 10,
color='r',
transform=ax.transAxes)
plt.show()
使用來自 @ https://pythonguides.com/add-text-to-plot-matplotlib/的代碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.