2017-02-20 201 views
3

我常常想突出一起使用matplotlib做一個情節,看起來像一個曲線的一個點: Basic PlotMatplotlib指示點在X軸和Y軸

下面的代碼被用於創建情節

import numpy as np 
import matplotlib.pyplot as plt 
import seaborn as sns 

y = np.array([0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100])/100. 
x = 100. - np.array([ 
    99.79,98.96,98.65,98.39,98.13,97.88,97.61,97.33,97.01,96.65,96.21, 
    95.72,95.16,94.46,93.52,92.31,90.66,88.48,84.04,79.34,19.32]) 
ax = plt.subplot(111) 
line = plt.plot(x,y) 


def highlight_point(ax,line,point,linestyle=':'): 
    c = line.get_color() 
    xmin = ax.get_xlim()[0] 
    ymin = ax.get_ylim()[0] 

    ax.plot([xmin,point[0]],[point[1],point[1]],color=c,linestyle=linestyle) 
    ax.plot([point[0],point[0]],[ymin,point[1]],color=c,linestyle=linestyle) 

plt.xlim([0,85]) 
plt.ylim([0,1]) 
highlight_point(ax,line[0],[x[10],y[10]]) 
plt.show() 

上述方法在xlimylim未能輸入時,或者稍後將另一個圖添加到圖中時失敗。我想要一些axhlinehlines的組合,其中我可以指定繪圖的左側/底部到某個數學點。

+0

有可能實際上是使用某種混合變換的選項構成線條的點。然而,由於4個座標系中只有1個座標軸系統存在,而其他三個座標系統存在於數據系統中,所以我不知道如何實現這一點。 – ImportanceOfBeingErnest

+0

「我可以用小網格點攻擊這個」是什麼意思? – ImportanceOfBeingErnest

回答

2

一種方法可以是每次畫布重繪時更新行。爲此,我們可以使用連接到draw_event偵聽器的更新方法創建類PointMarkers。通過這種方式,線不僅會在標記線創建之後添加點,而且會在畫布調整大小或平移時更新。

import numpy as np 
import matplotlib.pyplot as plt 
import seaborn as sns 

class PointMarker(): 
    def __init__(self, ax, point, **kwargs): 
     self.ax = ax 
     self.point = point 
     if "line" in kwargs: 
      self.c = kwargs.get("line").get_color() 
     else: 
      self.c = kwargs.get("color", "b") 
     self.ls=kwargs.get("linestyle", ':') 
     self.vline, = self.ax.plot([],[],color=self.c,linestyle=self.ls) 
     self.hline, = self.ax.plot([],[],color=self.c,linestyle=self.ls) 
     self.draw() 

    def draw(self): 
     xmin = ax.get_xlim()[0] 
     ymin = ax.get_ylim()[0] 
     self.vline.set_data([self.point[0], self.point[0]], [ymin,self.point[1]]) 
     self.hline.set_data([xmin, self.point[0]], [self.point[1], self.point[1]]) 

class PointMarkers(): 
    pointmarkers = [] 
    def add(self,ax, point, **kwargs): 
     pm = PointMarker(ax, point, **kwargs) 
     self.pointmarkers.append(pm) 
    def update(self, event=None): 
     for pm in self.pointmarkers: 
      pm.draw() 

x = np.arange(1,17) 
y = np.log(x) 
ax = plt.subplot(111) 
line = plt.plot(x,y) 

# register the markers 
p = PointMarkers() 
p.add(ax,[x[5],y[5]], line=line[0]) 
p.add(ax,[x[12],y[12]], color="purple", linestyle="-.") 
# connect event listener 
cid = plt.gcf().canvas.mpl_connect("draw_event", p.update) 

#testing: draw some new points or change axis limits 
plt.plot([5,11],[-0.5,0.6]) 
#plt.xlim([0,85]) 
#plt.ylim([0,1]) 

plt.show() 

enter image description here

保存,重繪將需要直接的save命令之前手動進行的,像

plt.gcf().canvas.draw() 
plt.savefig(...)