簡體   English   中英

pyplot:在軸上添加點投影

[英]pyplot: adding point projections on axis

我可以使用 plot function 繪制圖表。 但是我想通過在軸上繪制投影並將文本放在點和軸上來突出顯示一些“特殊”點。

像這樣的東西: 在此處輸入圖像描述

我試過這個:

import matplotlib.pyplot as plt

[...]
plt.plot(X, Y, label='data')  # draw curve, X and Y are arrays
plt.plot(Xp, Yp, c, duration), marker='o') # draw point @(Xp, Yp), Xp and Yp are scalars
plt.vlines(Xp, min(Y), Yp, linestyles='dashed')
plt.hlines(Yp, min(X), Xp, linestyles='dashed')
plt.grid(True)
plt.show()

但我得到的並不令人滿意:

在此處輸入圖像描述

得到我想要的東西的正確方法是什么?
我也考慮過annotate ,但它似乎沒有做我需要的。 如我錯了請糾正我。

您可以將annotate混合轉換一起使用:

import matplotlib.pyplot as plt

plt.plot([1,2], [2,4], label='data')
plt.plot([1.7], [3.4], marker='o')
plt.grid(True)

x,y = 1.7, 3.4
arrowprops={'arrowstyle': '-', 'ls':'--'}
plt.annotate(str(x), xy=(x,y), xytext=(x, 0), 
             textcoords=plt.gca().get_xaxis_transform(),
             arrowprops=arrowprops,
             va='top', ha='center')
plt.annotate(str(y), xy=(x,y), xytext=(0, y), 
             textcoords=plt.gca().get_yaxis_transform(),
             arrowprops=arrowprops,
             va='center', ha='right')

在此處輸入圖像描述

這並不完美,因為您可能仍需要手動調整軸坐標(例如-0.05而不是0 )以將標簽設置為偏離軸。

類似的東西可能就是您正在尋找的答案。 https://stackoverflow.com/a/14434334/14920085

y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123] #text that you want to print at the points
fig, ax = plt.subplots()
ax.scatter(z, y)
ax.set_ylabel('y')
ax.set_xlabel('x')
for i, txt in enumerate(n):
    ax.annotate(txt, (z[i], y[i]))

你需要玩弄一下xlimylim

對我來說,這很有效:

import matplotlib.pyplot as plt
import numpy as np

if __name__ == "__main__":
    X = np.linspace(-.5, 3, 100)
    Y = 15000 - 10 * (X - 2.2) ** 2
    Xp = X[-10]
    Yp = Y[-10]

    plt.plot(X, Y, label='data')
    plt.plot(Xp, Yp, marker='o')
    plt.vlines(Xp, min(Y), Yp, linestyles='dashed')
    plt.hlines(Yp, min(X), Xp, linestyles='dashed')
    plt.grid(True)
    plt.xlim(min(X), None)
    plt.ylim(min(Y), None)
    plt.show()

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM