Skip to content

Instantly share code, notes, and snippets.

@sungyongchoi
Last active April 1, 2016 02:24
Show Gist options
  • Save sungyongchoi/f50ee13f210592fc24ee to your computer and use it in GitHub Desktop.
Save sungyongchoi/f50ee13f210592fc24ee to your computer and use it in GitHub Desktop.
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.cbook as cbook
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import Tkinter as Tk
import tkFileDialog
import os
import csv
import math
def fmt(x, y):
return 'x: {x:0.4f}\ny: {y:0.4f}'.format(x = x, y = y)
class DataCursor(object):
# http://stackoverflow.com/a/4674445/190597
"""A simple data cursor widget that displays the x,y location of a
matplotlib artist when it is selected."""
def __init__(self, artists, x = [], y = [], tolerance = 5, offsets = (-20, 20),
formatter = fmt, display_all = False):
"""Create the data cursor and connect it to the relevant figure.
"artists" is the matplotlib artist or sequence of artists that will be
selected.
"tolerance" is the radius (in points) that the mouse click must be
within to select the artist.
"offsets" is a tuple of (x,y) offsets in points from the selected
point to the displayed annotation box
"formatter" is a callback function which takes 2 numeric arguments and
returns a string
"display_all" controls whether more than one annotation box will
be shown if there are multiple axes. Only one will be shown
per-axis, regardless.
"""
self._points = np.column_stack((x,y))
self.formatter = formatter
self.offsets = offsets
self.display_all = display_all
if not cbook.iterable(artists):
artists = [artists]
self.artists = artists
self.axes = tuple(set(art.axes for art in self.artists))
self.figures = tuple(set(ax.figure for ax in self.axes))
self.annotations = {}
for ax in self.axes:
self.annotations[ax] = self.annotate(ax)
for artist in self.artists:
artist.set_picker(tolerance)
for fig in self.figures:
fig.canvas.mpl_connect('pick_event', self)
def annotate(self, ax):
"""Draws and hides the annotation box for the given axis "ax"."""
annotation = ax.annotate(self.formatter, xy = (0, 0), ha = 'right',
xytext = self.offsets, textcoords = 'offset points', va = 'bottom',
bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0')
)
annotation.set_visible(False)
return annotation
def snap(self, x, y):
"""Return the value in self._points closest to (x, y).
"""
idx = np.nanargmin(((self._points - (x,y))**2).sum(axis = -1))
return self._points[idx]
def __call__(self, event):
"""Intended to be called through "mpl_connect"."""
# Rather than trying to interpolate, just display the clicked coords
# This will only be called if it's within "tolerance", anyway.
x, y = event.mouseevent.xdata, event.mouseevent.ydata
annotation = self.annotations[event.artist.axes]
if x is not None:
if not self.display_all:
# Hide any other annotation boxes...
for ann in self.annotations.values():
ann.set_visible(False)
# Update the annotation in the current axis..
x, y = self.snap(x, y)
annotation.xy = x, y
annotation.set_text(self.formatter(x, y))
annotation.set_visible(True)
event.canvas.draw()
class Index(object):
ind = 0
def open(self, event):
folder = tkFileDialog.askopenfilename() # show an "Open" dialog box and return the path to the selected file
f= open(folder)
#append values to list
for row in csv.reader(f):
x.append( float (row[0] ) )
y.append( float (row[1] ) )
scat = ax.scatter(x, y)
event.canvas.draw()
def height(self, event):
scat = ax.scatter(x, y)
DataCursor(scat, x, y)
x=[]
y=[]
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2)
callback = Index()
axopen = plt.axes([0.59, 0.05, 0.1, 0.075])
bopen = Button(axopen, 'Open')
bopen.on_clicked(callback.open)
axheight = plt.axes([0.81, 0.05, 0.1, 0.075])
bheight = Button(axheight, 'distance')
bheight.on_clicked(callback.height)
plt.show()
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.cbook as cbook
import numpy as np
import Tkinter as Tk
import tkFileDialog
import os
import csv
import math
def fmt(x, y):
return 'x: {x:0.4f}\ny: {y:0.4f}'.format(x = x, y = y)
class DataCursor(object):
# http://stackoverflow.com/questions/13306519/get-data-from-plot-with-matplotlib
"""A simple data cursor widget that displays the x,y location of a
matplotlib artist when it is selected."""
def __init__(self, artists, x = [], y = [], tolerance = 5, offsets = (-20, 20),
formatter = fmt, display_all = False):
"""Create the data cursor and connect it to the relevant figure.
"artists" is the matplotlib artist or sequence of artists that will be
selected.
"tolerance" is the radius (in points) that the mouse click must be
within to select the artist.
"offsets" is a tuple of (x,y) offsets in points from the selected
point to the displayed annotation box
"formatter" is a callback function which takes 2 numeric arguments and
returns a string
"display_all" controls whether more than one annotation box will
be shown if there are multiple axes. Only one will be shown
per-axis, regardless.
"""
self._points = np.column_stack((x,y))
self.formatter = formatter
self.offsets = offsets
self.display_all = display_all
if not cbook.iterable(artists):
artists = [artists]
self.artists = artists
self.axes = tuple(set(art.axes for art in self.artists))
self.figures = tuple(set(ax.figure for ax in self.axes))
self.annotations = {}
for ax in self.axes:
self.annotations[ax] = self.annotate(ax)
for artist in self.artists:
artist.set_picker(tolerance)
for fig in self.figures:
fig.canvas.mpl_connect('pick_event', self)
def annotate(self, ax):
"""Draws and hides the annotation box for the given axis "ax"."""
annotation = ax.annotate(self.formatter, xy = (0, 0), ha = 'right',
xytext = self.offsets, textcoords = 'offset points', va = 'bottom',
bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0')
)
annotation.set_visible(False)
return annotation
def snap(self, x, y):
"""Return the value in self._points closest to (x, y).
"""
idx = np.nanargmin(((self._points - (x,y))**2).sum(axis = -1))
return self._points[idx]
def __call__(self, event):
"""Intended to be called through "mpl_connect"."""
# Rather than trying to interpolate, just display the clicked coords
# This will only be called if it's within "tolerance", anyway.
x, y = event.mouseevent.xdata, event.mouseevent.ydata
annotation = self.annotations[event.artist.axes]
if x is not None:
if not self.display_all:
# Hide any other annotation boxes...
for ann in self.annotations.values():
ann.set_visible(False)
# Update the annotation in the current axis..
x, y = self.snap(x, y)
annotation.xy = x, y
annotation.set_text(self.formatter(x, y))
annotation.set_visible(True)
event.canvas.draw()
x=[]
y=[]
folder = tkFileDialog.askopenfilename() # show an "Open" dialog box and return the path to the selected file
f= open(folder)
#append values to list
for row in csv.reader(f):
x.append(float(row[0]))
y.append(float(row[1]))
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
scat = ax.scatter(x, y)
DataCursor(scat, x, y)
plt.show()
import heapq
import operator
import math
import numpy as np
x1 = float ( raw_input('What is first X1? ' ) )
y1 = float ( raw_input('What is first Y1? ' ) )
x2 = float ( raw_input('What is first X2? ' ) )
y2 = float ( raw_input('What is first Y2? ' ) )
x0 = float ( raw_input('What is first X0? ' ) )
y0 = float ( raw_input('What is first Y0? ' ) )
molecule = abs( (y2-y1)*x0 - (x2-x1)*y0 + x2*y1 - y2*x1 )
denominator = math.sqrt ( (y2-y1)**2+(x2-x1)**2 )
distance = ( molecule / denominator )
print distance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment