I created an interactive scatterplot using bqplot where you are allowed to drag points around (using enable_move=True).
I don't want the user to drag points above the line y=x.
If they do, I want the point to snap back to where it was most recently.
The problem is that I'm not sure how to avoid infinite recursion here.
The scatterplot needs to be aware of when its points are moved in order to check the move and possibly snap back.
However, when it begins to snap back, this change (of the point positions) seems to trigger that same callback.
Can anyone tell me the "correct" way to deal with this basic issue?
import bqplot.pyplot as plt
import numpy as np
def on_point_move(change, scat):
if np.any(newx < scat.y):
scat.x = change['old']
fig = plt.figure(animation_duration=400)
xs = 1.0*np.arange(3) # make sure these are floats
ys = 1.0*np.arange(3)
scat = plt.scatter(xs, ys, colors=['Red'], default_size=400, enable_move=True)
scat.observe(lambda change: on_point_move(change, scat), names=['x'])
fig
You can temporarily disable the observe in the on_point_move function. I've changed the logic a bit too.
import bqplot.pyplot as plt
import numpy as np
def on_point_move(change):
if np.any(scat.x < scat.y):
scat.unobserve_all()
if change['name'] == 'x':
scat.x = change['old']
elif change['name'] == 'y':
scat.y = change['old']
scat.observe(on_point_move, names=['x','y'])
fig = plt.figure(animation_duration=400)
xs = 1.0*np.arange(3) # make sure these are floats
ys = 1.0*np.arange(3)
scat = plt.scatter(xs, ys, colors=['Red'], default_size=400, enable_move=True)
scat.observe(on_point_move, names=['x','y'])
fig
Related
Using the Zoom Line Example I have made a Python QChartView class that can scroll with the arrow keys and zoom with the plus and minus keys. (see my code below).
When I scroll left I would expect that the grid lines and axis ticks scroll the same amount as the data. However, only the data (the QLineSeries) scrolls to the left. The 5 grid lines remain at the same positions but their tick values are updated. This is undesirable as the new tick values can be anything.
I have looked in the documentation but could not find how to make the grid scroll together with the data. Am I missing something?
I would also like to be able to set the ticks to explicit values (so that I can perhaps implement the scrolling behavior myself). Is it possible to set the axis tick values to specific values?
My example code:
import sys
from math import pi, sin, sqrt
from PyQt5.QtChart import QLineSeries, QChart, QChartView
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication
class ZoomPanChartView(QChartView):
""" QChartView that can zoom/pan with the keys
"""
def __init__(self, chart):
super().__init__(chart)
self.zoomFactor = sqrt(2) # QCharts default is 2
self.panPixels = 10
def keyPressEvent(self, keyEvent):
""" Panning (scrolling) is done with the arrow keys.
Zooming goes with the plus and minus keys.
The '=' key resets.
"""
key = keyEvent.key()
if key == Qt.Key_Equal:
self.chart().zoomReset()
if key == Qt.Key_Plus:
self.chart().zoom(self.zoomFactor)
elif key == Qt.Key_Minus:
self.chart().zoom(1/self.zoomFactor)
elif key == Qt.Key_Left:
self.chart().scroll(-self.panPixels, 0)
elif key == Qt.Key_Right:
self.chart().scroll(+self.panPixels, 0)
elif key == Qt.Key_Up:
self.chart().scroll(0, +self.panPixels)
elif key == Qt.Key_Down:
self.chart().scroll(0, -self.panPixels)
elif key == Qt.Key_0:
self.chart().axisX().applyNiceNumbers() # changes the range
else:
super().keyPressEvent(keyEvent)
def main():
app = QApplication(sys.argv)
chart = QChart()
series = QLineSeries()
for i in range(0, 100):
x = i * pi / 20
y = sin(x)
series.append(x, y)
chart.addSeries(series)
chart.createDefaultAxes()
chart.axisY().setRange(-1, 1)
chart.legend().hide()
chartView = ZoomPanChartView(chart)
chartView.show()
chartView.resize(400, 300)
sys.exit(app.exec_())
if __name__ == "__main__":
main()
You can use QCategoryAxis to place ticks where you want:
initialize:
ch = self.chView.chart()
self.chartAxisX = QCategoryAxis(labelsPosition=QCategoryAxis.AxisLabelsPositionOnValue, startValue=0.0)
ch.setAxisX(self.chartAxisX)
self.chartAxisY = QCategoryAxis(labelsPosition=QCategoryAxis.AxisLabelsPositionOnValue, startValue=0.0)
ch.setAxisY(self.chartAxisY)
add series:
ch.addSeries(s)
s.attachAxis(self.chartAxisX)
s.attachAxis(self.chartAxisY)
set ticks at multiples of 5:
for s in self.chartAxisX.categoriesLabels():
self.chartAxisX.remove(s)
for i in range(0, int(max_x_value) + 1, 5):
self.chartAxisX.append(str(i), i)
self.chartAxisX.setRange(0.0, max_x_value)
or use this generic function for any interval:
def format_axis(axis, min_value, max_value, step):
for s in axis.categoriesLabels():
axis.remove(s)
axis.setStartValue(min_value)
for i in range(ceil(min_value / step), floor(max_value / step) + 1):
v = i * step
axis.append('%g' % v, v)
axis.setRange(min_value, max_value)
format_axis(self.chartAxisX, -1.1, 0.98, 0.25)
The best I could find is setting a QValueAxis as the axis on QChart and calling QValueAxis::applyNiceNumbers() to adjust the range, i.e. max and min of the current scale, so that the numbers shown are a bit more human readable. But this will alter data's position instead of gridlines' positions. You can check the function's behaviour on the horizontalBarChart example.
I thought of using a QLineSeries data-set to make the grid myself, but I would need to change the tick's positions on the axis, which, as far as I was able to determine, is not easily made with current QChart.
Short answer: you can't do it with QCharts..
I've been working with Qwt library for some time and I can attest that the grid there behaves as expected and other behaviors are a bit more mature as well. Panning moves the grip around and zooming makes the grid resize in steps to stay human-readable. Maybe it's worth checking.
IMO you can do this with QCharts and QValueAxis:
QValueAxis *axisY = new QValueAxis;
axisY->setTickType(QValueAxis::TicksDynamic);
axisY->setTickAnchor(0.0);
axisY->setTickInterval(0.2);
See e.g. Nice Label Algoritm on how to determine nice tick intervals.
In a web app, I would like to let the user select a region of interest in a plotted image using the nice box/lasso selection tools of bokeh. I would the like to receive the selected pixels for further operations in python.
For scatter plots, this is easy to do in analogy with the gallery,
import bokeh.plotting
import numpy as np
# data
X = np.linspace(0, 10, 20)
def f(x): return np.random.random(len(x))
# plot and add to document
fig = bokeh.plotting.figure(x_range=(0, 10), y_range=(0, 10),
tools="pan,wheel_zoom,box_select,lasso_select,reset")
plot = fig.scatter(X, f(X))
#plot = fig.image([np.random.random((10,10))*255], dw=[10], dh=[10])
bokeh.plotting.curdoc().add_root(fig)
# callback
def callback(attr, old, new):
# easily access selected points:
print sorted(new['1d']['indices'])
print sorted(plot.data_source.selected['1d']['indices'])
plot.data_source.data = {'x':X, 'y':f(X)}
plot.data_source.on_change('selected', callback)
however if I replace the scatter plot with
plot = fig.image([np.random.random((10,10))*255], dw=[10], dh=[10])
then using the selection tools on the image does not change anything in plot.data_source.selected.
I'm sure this is the intended behavior (and it makes sense too), but what if I want to select pixels of an image? I could of course put a grid of invisible scatter points on top of the image, but is there some more elegant way to accomplish this?
It sounds like the tool you're looking for is actually the BoxEditTool. Note that the BoxEditTool requires a list of glyphs (normally these will be Rect instances) that will render the ROIs, and that listening to changes should be set using:
rect_glyph_source.on_change('data', callback)
This will trigger the callback function any time you make any changes to your ROIs.
The relevant ColumnDataSource instance (rect_glyph_source in this example) will be updated so that the 'x' and 'y' keys list the center of each ROI in the image's coordinates space, and of course 'width' and 'height' describe its size. As far as I know there isn't currently a built-in method for extracting the data itself, so you will have to do something like:
rois = rect_glyph_source.data
roi_index = 0 # x, y, width and height are lists, and each ROI has its own index
x_center = rois['x'][roi_index]
width = rois['width'][roi_index]
y_center = rois['y'][roi_index]
height = rois['height'][roi_index]
x_start = int(x_center - 0.5 * width)
x_end = int(x_center + 0.5 * width)
y_start = int(y_center - 0.5 * height)
y_end = int(y_center + 0.5 * height)
roi_data = image_plot.source.data['image'][0][y_start:y_end, x_start:x_end]
IMPORTANT: In the current version of Bokeh (0.13.0) there is a problem with the synchronization of the BoxEditTool at the server and it isn't functional. This should be fixed in the next official Bokeh release. For more information and a temporary solution see this answer or this discussion.
i tried to express the trajectory of bullet when there is a drag force.
however, i am not able to express the graph precisely.
how to depict trajectory from ode equation?.
this is my graph. this graph does not plausible. although i struggled setting different sign of vydot value, this is not working correctly.
from pylab import*
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import numpy as np
g=10
m=1
k=0.01
y=zeros([2])
vy0=0
vydot=200
vx0=0
vxdot=200
y[0]=vy0
y[1]=vydot
x=zeros([2])
x[0]=vx0
x[1]=vxdot
t=linspace(0,1000,5000)
def fy(y,t):
g0=y[1]
g1=-k*y[1]
return array([g0,g1])
def fx(z,t):
g0=-x[1]
g1=-k*(x[1])-g
return array([g0,g1])
ans1=odeint(fy,y,t)
ans2=odeint(fx,x,t)
ydata=(ans1[:,])
xdata=(ans2[:,])
plt.plot(ydata,xdata)
show()"""
In air, as opposed to liquids, the bullet not only displaces the volume along its path, but also increases the impulse of the displaced air molecules proportional to the velocity. Thus the drag force is
vn=sqrt(vx²+vy²)
dragx = -k*vn*vx
dragy = -k*vn*vy
Thus use
def f(z,t):
x,y,vx,vy = z
vn = sqrt(vx*vx+vy*vy)
return array([vx, vy, -k*vn*vx, -k*vn*vy-g ])
For a first overview, consider the problem without drag. Then the solution is
x(t) = vx*t = 200m/s*t
y(t) = vy*t-g/2*t² = 200m/s*t - 5m/s²*t²
y(t)=0 is again met for t=2*vy/g at the x coordinate 2*vx*vy/g = 8000m. Maximum height is reached for t=vy/g at height vy²/(2g)=2000m.
I've been working with Sympy for an Interpolation, in which I obtain as a result a 7th degree Polynomial (ax^7 + bx^6 + cx^5 + ...+ h) which I want to Plot, but wen I try to plot it I get errors, for example, if I try:
plt.plot(r,U.subs(x,r))
where r = np.linspace(0,20,num=100) and U = Polynomial(x);
the result is an error message: ValueError: sequence too large; must be smaller than 32, I obtain MemoryError: if I try `r = np.arange(20)'. The only way I could plot it is with a for cycle, substituting one by one and saving it in another variable as a list. So my question is, what is wrong with the first's inputs? is there an easy way to plot a polynomial?
Welcome to SO!
The subs() method is not meant to be used with numpy arrays. lambdify() does what you want. Try:
import numpy as np
import matplotlib.pyplot as plt
import sympy as sy
sy.init_printing() # nice formula rendering in IPython
x = sy.symbols("x", real=True)
# the sample polynomial:
pp = x**3 + 3*x**2 - 6*x - 8
# Convert expression function usable with numpy array:
f_pp = sy.lambdify(x, pp, modules=np)
# Do the plotting:
x_n = np.linspace(-5, 2, 500)
y_n = f_pp(x_n) # evaluate all x_n
fg, ax = plt.subplots(1, 1)
ax.plot(x_n, y_n)
fg.canvas.draw()
plt.show()
The parameter modules=np ensures, that numpy is used for functions in the expression (e.g., sin() => np.sin()). In this example, it is not explicitly needed.
PS: If you include a runnable example in your question, it makes live much easier for potential answerers.
I am using matplotlib to fit some data to a grid and plot it as a polar projection. Something like in the example below. However, I want it to be smooth where the edges of the plot meet at 0/360 degrees. Anyone know how I do this??
from pylab import *
import random
x = linspace(0, 360, 361).astype(int)
x = x*pi/180
y = linspace(0.05, 0.5, 800)
xgrid, ygrid = meshgrid(x, y)
baz = []
for c in range(2000): baz.append(random.randint(0,360))
freq = rand(len(baz))
pwr = rand(len(baz))
zgrid = griddata(baz,freq,pwr, xgrid, ygrid)
subplot(111, polar=True)
pcolormesh(xgrid, ygrid, zgrid)
show()
Also the data I am working with has a gap due to the mask created by griddata (I use griddata as above but then sum many grids in a loop). I would like to fill the missing segment (see attached fig), does anyone know how to do this?
thanks
Dave
If you know which grids come together at the 0/360 degree position you could just concatenate them and do a spline interpolation on it (scipy interpolation).
For your second problem I am not sure but how about creating your grids in polar coordinates? Would this solve your problem?
Kind regards