Related
I am learning how to create plots with slider bars. Here is my code based off the first example of this tutorial
using Plots
gr()
using GLMakie
function plotLaneEmden(log_delta_xi=-4, n=3)
fig = Figure()
ax = Axis(fig[1, 1])
sl_x = Slider(fig[2, 1], range = 0:0.01:4.99, startvalue = 3)
sl_y = Slider(fig[1, 2], range = -6:0.01:0.1, horizontal = false, startvalue = -2)
point = lift(sl_x.value, sl_y.value) do n, log_delta_xi
Point2f(n, log_delta_xi)
end
plot(n, 1 .- log_delta_xi.^2/6, linecolor = :green, label="n = $n")
xlabel!("ξ")
ylabel!("θ")
end
plotLaneEmden()
When I run this, it gives UndefVarError: plot not defined. What am I missing here?
It looks like you are trying to mix and match Plots.jl and Makie.jl. Specifically, the example from your link is entirely for Makie (specifically, with the GLMakie backend), while the the plot function you are trying to add uses syntax specific to the Plots.jl version of plot (specifically including linecolor and label keyword arguments).
Plots.jl and Makie.jl are two separate and unrelated plotting libraries, so you have to pick one and stick with it. Since both libraries export some of the same function names, using both at once will lead to ambiguity and UndefVarErrors if not disambiguated.
The other potential problem is that it looks like you are trying to make a line plot with only a single x and y value (n and log_delta_xi are both single numbers in your code as written). If that's what you want, you'll need a scatter plot instead of a line plot; and if that's not what you want you'll need to make those variables vectors instead somehow.
Depending on what exactly you want, you might try something more along the lines of (in a new session, using only Makie and not Plots):
using GLMakie
function plotLaneEmden(log_delta_xi=-4, n=3)
fig = Figure()
ax = Axis(fig[1, 1], xlabel="ξ", ylabel="θ")
sl_x = Slider(fig[2, 1], range = 0:0.01:4.99, startvalue = n)
sl_y = Slider(fig[1, 2], range = -6:0.01:0.1, horizontal = false, startvalue = log_delta_xi)
point = lift(sl_x.value, sl_y.value) do n, log_delta_xi
Point2f(n, 1 - log_delta_xi^2/6)
end
sca = scatter!(point, color = :green, markersize = 20)
axislegend(ax, [sca], ["n = $n"])
fig
end
plotLaneEmden()
Or, below, a simple example for interactively plotting a line rather than a point:
using GLMakie
function quadraticsliders(x=-5:0.01:5)
fig = Figure()
ax = Axis(fig[1, 1], xlabel="X", ylabel="Y")
sl_a = Slider(fig[2, 1], range = -3:0.01:3, startvalue = 0.)
sl_b = Slider(fig[1, 2], range = -3:0.01:3, horizontal = false, startvalue = 0.)
points = lift(sl_a.value, sl_b.value) do a, b
Point2f.(x, a.*x.^2 .+ b.*x)
end
l = lines!(points, color = :blue)
onany((a,b)->axislegend(ax, [l], ["$(a)x² + $(b)x"]), sl_a.value, sl_b.value)
limits!(ax, minimum(x), maximum(x), -10, 10)
fig
end
quadraticsliders()
ETA: A couple examples closer to what you might be looking for
I have a set of 3D points and need to fit the best fitting plane which I am doing with the following code (found on stackoverflow):
points = np.reshape(points, (np.shape(points)[0], -1))
assert points.shape[0] <= points.shape[1], "There are only {} points in {} dimensions.".format(points.shape[1], points.shape[0])
ctr = points.mean(axis=1)
x = points - ctr[:, np.newaxis]
M = np.dot(x, x.T)
return ctr, svd(M)[0][:,-1] # return point and normal vector
Afterwards I want to display the plane in VTK. The problem is I have to scale the plane, but when I do so the plane is translated as well. How can I prevent that from happening ?
def create_vtk_plane_actor(point, normal_vector):
print("\n Display plane with point: %s and vector: %s" % (point, normal_vector))
plane_source = vtk.vtkPlaneSource()
plane_source.SetOrigin(point[0], point[1], point[2])
plane_source.SetNormal(normal_vector[0], normal_vector[1], normal_vector[2])
plane_source.Update()
transform = vtk.vtkTransform()
transform.Scale(1.5, 1.5, 1.0)
transform_filter = vtk.vtkTransformFilter()
transform_filter.SetInputConnection(plane_source.GetOutputPort())
transform_filter.SetTransform(transform)
actor = vtk.vtkActor()
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(transform_filter.GetOutputPort())
The scale is not applied on some coordinates local to your plan but on those you set. So indeed, the center will move. If you want to let it, you need to set a Translate on your transform.
Fitting planes is a builtin feature in vtkplotter, scaling is done with mesh.scale():
from vtkplotter import *
from vtkplotter import datadir
from vtkplotter.pyplot import histogram
plt = Plotter()
apple = load(datadir+"apple.ply").subdivide().addGaussNoise(1)
plt += apple.alpha(0.1)
variances = []
for i, p in enumerate(apple.points()):
pts = apple.closestPoint(p, N=12) # find the N closest points to p
plane = fitPlane(pts) # find the fitting plane and scale
variances.append(plane.variance)
if i % 400: continue
print(i, plane.variance)
plt += plane.scale(2)
plt += Points(pts)
plt += Arrow(plane.center, plane.center+plane.normal/10)
plt += histogram(variances).scale(6).pos(1.2,.2,-1)
plt.show()
I'm trying to do something that I'd normally consider trivial but seems to be very difficult in bokeh: Adding a vertical colorbar to a plot and then having the title of the colorbar (a.k.a. the variable behind the colormapping) appear to one side of the colorbar but rotated 90 degrees clockwise from horizontal.
From what I can tell of the bokeh ColorBar() interface (looking at both documentation and using the python interpreter's help() function for this element), this is not possible. In desperation I have added my own Label()-based annotation. This works but is klunky and displays odd behavior when deployed in a bokeh serve situation--that the width of the data window on the plot varies inversely with the length of the title colorbar's title string.
Below I've included a modified version of the bokeh server mpg example. Apologies for its complexity, but I felt this was the best way to illustrate the problem using infrastructure/data that ships with bokeh. For those unfamiliar with bokeh serve, this code snippet needs to saved to a file named main.py that resides in a directory--for the sake of argument let's say CrossFilter2--and in the parent directory of CrossFilter2 one needs to invoke the command
bokeh serve --show CrossFilter2
this will then display in a browser window (localhost:5006/CrossFilter2) and if you play with the color selection widget you will see what I mean, namely that short variable names such as 'hp' or 'mpg' result in a wider data display windows than longer variable names such as 'accel' or 'weight'. I suspect that there may be a bug in how label elements are sized--that their x and y dimensions are swapped--and that bokeh has not understood that the label element has been rotated.
My questions are:
Must I really have to go to this kind of trouble to get a simple colorbar label feature that I can get with little-to-no trouble in matplotlib/plotly?
If I must go through the hassle you can see in my sample code, is there some other way I can do this that avoids the data window width problem?
import numpy as np
import pandas as pd
from bokeh.layouts import row, widgetbox
from bokeh.models import Select
from bokeh.models import HoverTool, ColorBar, LinearColorMapper, Label
from bokeh.palettes import Spectral5
from bokeh.plotting import curdoc, figure, ColumnDataSource
from bokeh.sampledata.autompg import autompg_clean as df
df = df.copy()
SIZES = list(range(6, 22, 3))
COLORS = Spectral5
# data cleanup
df.cyl = df.cyl.astype(str)
df.yr = df.yr.astype(str)
columns = sorted(df.columns)
discrete = [x for x in columns if df[x].dtype == object]
continuous = [x for x in columns if x not in discrete]
quantileable = [x for x in continuous if len(df[x].unique()) > 20]
def create_figure():
xs = df[x.value].tolist()
ys = df[y.value].tolist()
x_title = x.value.title()
y_title = y.value.title()
name = df['name'].tolist()
kw = dict()
if x.value in discrete:
kw['x_range'] = sorted(set(xs))
if y.value in discrete:
kw['y_range'] = sorted(set(ys))
kw['title'] = "%s vs %s" % (y_title, x_title)
p = figure(plot_height=600, plot_width=800,
tools='pan,box_zoom,wheel_zoom,lasso_select,reset,save',
toolbar_location='above', **kw)
p.xaxis.axis_label = x_title
p.yaxis.axis_label = y_title
if x.value in discrete:
p.xaxis.major_label_orientation = pd.np.pi / 4
if size.value != 'None':
groups = pd.qcut(df[size.value].values, len(SIZES))
sz = [SIZES[xx] for xx in groups.codes]
else:
sz = [9] * len(xs)
if color.value != 'None':
coloring = df[color.value].tolist()
cv_95 = np.percentile(np.asarray(coloring), 95)
mapper = LinearColorMapper(palette=Spectral5,
low=cv_min, high=cv_95)
mapper.low_color = 'blue'
mapper.high_color = 'red'
add_color_bar = True
ninety_degrees = pd.np.pi / 2.
color_bar = ColorBar(color_mapper=mapper, title='',
#title=color.value.title(),
title_text_font_style='bold',
title_text_font_size='20px',
title_text_align='center',
orientation='vertical',
major_label_text_font_size='16px',
major_label_text_font_style='bold',
label_standoff=8,
major_tick_line_color='black',
major_tick_line_width=3,
major_tick_in=12,
location=(0,0))
else:
c = ['#31AADE'] * len(xs)
add_color_bar = False
if add_color_bar:
source = ColumnDataSource(data=dict(x=xs, y=ys,
c=coloring, size=sz, name=name))
else:
source = ColumnDataSource(data=dict(x=xs, y=ys, color=c,
size=sz, name=name))
if add_color_bar:
p.circle('x', 'y', fill_color={'field': 'c',
'transform': mapper},
line_color=None, size='size', source=source)
else:
p.circle('x', 'y', color='color', size='size', source=source)
p.add_tools(HoverTool(tooltips=[('x', '#x'), ('y', '#y'),
('desc', '#name')]))
if add_color_bar:
color_bar_label = Label(text=color.value.title(),
angle=ninety_degrees,
text_color='black',
text_font_style='bold',
text_font_size='20px',
x=25, y=300,
x_units='screen', y_units='screen')
p.add_layout(color_bar, 'right')
p.add_layout(color_bar_label, 'right')
return p
def update(attr, old, new):
layout.children[1] = create_figure()
x = Select(title='X-Axis', value='mpg', options=columns)
x.on_change('value', update)
y = Select(title='Y-Axis', value='hp', options=columns)
y.on_change('value', update)
size = Select(title='Size', value='None',
options=['None'] + quantileable)
size.on_change('value', update)
color = Select(title='Color', value='None',
options=['None'] + quantileable)
color.on_change('value', update)
controls = widgetbox([x, y, color, size], width=200)
layout = row(controls, create_figure())
curdoc().add_root(layout)
curdoc().title = "Crossfilter"
You can add a vertical label to the Colorbar by plotting it on a separate axis and adding a title to this axis. To illustrate this, here's a modified version of Bokeh's standard Colorbar example (found here):
import numpy as np
from bokeh.plotting import figure, output_file, show
from bokeh.models import LogColorMapper, LogTicker, ColorBar
from bokeh.layouts import row
plot_height = 500
plot_width = 500
color_bar_height = plot_height + 11
color_bar_width = 180
output_file('color_bar.html')
def normal2d(X, Y, sigx=1.0, sigy=1.0, mux=0.0, muy=0.0):
z = (X-mux)**2 / sigx**2 + (Y-muy)**2 / sigy**2
return np.exp(-z/2) / (2 * np.pi * sigx * sigy)
X, Y = np.mgrid[-3:3:100j, -2:2:100j]
Z = normal2d(X, Y, 0.1, 0.2, 1.0, 1.0) + 0.1*normal2d(X, Y, 1.0, 1.0)
image = Z * 1e6
color_mapper = LogColorMapper(palette="Viridis256", low=1, high=1e7)
plot = figure(x_range=(0,1), y_range=(0,1), toolbar_location=None,
width=plot_width, height=plot_height)
plot.image(image=[image], color_mapper=color_mapper,
dh=[1.0], dw=[1.0], x=[0], y=[0])
Now, to make the Colorbar, create a separate dummy plot, add the Colorbar to the dummy plot and place it next to the main plot. Add the Colorbar label as the title of the dummy plot and center it appropriately.
color_bar = ColorBar(color_mapper=color_mapper, ticker=LogTicker(),
label_standoff=12, border_line_color=None, location=(0,0))
color_bar_plot = figure(title="My color bar title", title_location="right",
height=color_bar_height, width=color_bar_width,
toolbar_location=None, min_border=0,
outline_line_color=None)
color_bar_plot.add_layout(color_bar, 'right')
color_bar_plot.title.align="center"
color_bar_plot.title.text_font_size = '12pt'
layout = row(plot, color_bar_plot)
show(layout)
This gives the following output image:
One thing to look out for is that color_bar_width is set wide enough to incorporate both the Colorbar, its axes labels and the Colorbar label. If the width is set too small, you will get an error and the plot won't render.
As of Bokeh 0.12.10 there is no built in label available for colorbars. In addition to your approach or something like it, another possibility would be a custom extension, though that is similarly not trivial.
Offhand, a colobar label certainly seems like a reasonable thing to consider. Regarding the notion that it ought to be trivially available, if you polled all users about what they consider should be trivially available, there will be thousands of different suggestions for what to prioritize. As is very often the case in the OSS world, there are far more possible things to do, than there are people to do them (less than 3 in this case). So, would first suggest a GitHub Issue to request the feature, and second, if you have the ability, volunteering to help implement it. Your contribution would be valuable and appreciated by many.
I'm trying to create an scrolling plot window with PyQtGraph. The plot itself has multiple axes. I used this as the basis of the multiple axes. I used this one as the base to do the scrolling bit.
My problem is that for my data, the scrolling plot seems to acquire an y-offset, increasing as time goes on. I also tried using the same data to display in an accumulating plot (though I really would rather to do a scrolling view) and it didn't acquire any y-offset.
This is what it looks at the end of my test sample - missing the effect of y-offset gradually increasing -
Of course, I would like for the y-offset not to appear, the top plot should be identical to the last 50 samples of the bottom plot
Both plots have identical data sets.
The code that I'm using to generate this is:
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
from time import sleep
win = pg.GraphicsWindow()
win.setWindowTitle('Sliding Window Test')
p1 = win.addPlot()
p1.setLabels(left='Large Range')
## create third ViewBox.
## this time we need to create a new axis as well.
p3 = pg.ViewBox()
ax3 = pg.AxisItem('right')
p1.layout.addItem(ax3, 2, 3)
p1.scene().addItem(p3)
ax3.linkToView(p3)
p3.setXLink(p1)
ax3.setZValue(-10000)
ax3.setLabel('Small Range', color='#ff0000')
win.nextRow()
p5 = win.addPlot()
p5.setLabels(left='Large Range')
## create third ViewBox.
## this time we need to create a new axis as well.
p7 = pg.ViewBox()
ax7 = pg.AxisItem('right')
p5.layout.addItem(ax7, 2, 3)
p5.scene().addItem(p7)
ax7.linkToView(p7)
p7.setXLink(p5)
ax7.setZValue(-10000)
ax7.setLabel('Small Range', color='#ff0000')
## Handle view resizing
def updateViews():
## view has resized; update auxiliary views to match
global p1, p3, p5, p7
p3.setGeometry(p1.vb.sceneBoundingRect())
p7.setGeometry(p5.vb.sceneBoundingRect())
## need to re-update linked axes since this was called
## incorrectly while views had different shapes.
## (probably this should be handled in ViewBox.resizeEvent)
p3.linkedViewChanged(p1.vb, p3.XAxis)
p7.linkedViewChanged(p5.vb, p7.XAxis)
updateViews()
p1.vb.sigResized.connect(updateViews)
p5.vb.sigResized.connect(updateViews)
data1 = []
data3 = []
curve1 = p1.plot()
curve3 = pg.PlotCurveItem(pen='r')
p3.addItem(curve3)
curve5 = p5.plot()
curve7 = pg.PlotCurveItem(pen='r')
p7.addItem(curve7)
data1 = [1000.0*r - 400 for r in np.random.random(size=600)]
data3 = [1.5*r for r in np.random.random(size=600)]
p1.setRange(yRange=(-400, 600))
p3.setRange(yRange=(0, 1.5))
p5.setRange(yRange=(-400, 600))
p7.setRange(yRange=(0, 1.5))
timer = pg.QtCore.QTimer()
r = 0
def update():
global timer
global r
if r > 50:
curve1.setData(data1[r-50:r])
curve3.setData(data3[r-50:r])
curve1.setPos(r - 50, r)
curve3.setPos(r - 50, r)
else:
curve1.setData(data1[:r])
curve3.setData(data3[:r])
curve5.setData(data1[:r])
curve7.setData(data3[:r])
r +=1
if r >= 600:
timer.stop()
timer.timeout.connect(update)
timer.start(100)
## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
Simple error: both curves in the top plot are shifted in the y-direction because of these lines:
curve1.setPos(r - 50, r)
curve3.setPos(r - 50, r)
They should instead look like:
curve1.setPos(r - 50, 0)
curve3.setPos(r - 50, 0)
I want to know how to arrange for the text on a ttk widget (a label or button, say) to resize automatically.
Changing the size of the text is easy, it is just a matter of changing the font in the style. However, hooking it into changes in the size of the window is a little more tricky. Looking on the web I found some hints, but there was nowhere a complete answer was posted.
So, here below is a complete working example posted as an answer to my own question. I hope someone finds it useful. If anyone has further improvements to suggest, I will be delighted to see them!
The example below shows two techniques, one activated by re-sizing the window (see the resize() method, bound to the <Configure> event), and the other by directly changing the size of the font (see the mutate() method).
Other code necessary to get resizing working is the grid configuration code in the __init__() method.
When running the example, there is some interaction between the two methods, but I think in a 'real' situation one technique would be sufficient, so that issue won't arise.
from tkinter import *
from tkinter.ttk import *
class ButtonApp(Frame):
"""Container for the buttons."""
def __init__(self, master=None):
"""Initialize the frame and its children."""
super().__init__(master)
self.createWidgets()
# configure the frame's resize behaviour
master.columnconfigure(0, weight=1)
master.rowconfigure(0, weight=1)
self.grid(sticky=(N,S,E,W))
# configure resize behaviour for the frame's children
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
# bind to window resize events
self.bind('<Configure>', self.resize)
def createWidgets(self):
"""Make the widgets."""
# this button mutates
self.mutantButton = Button(self, text='Press Me',
style='10.TButton')
self.mutantButton.grid(column=0, row=0, sticky=(N,S,E,W))
self.mutantButton['command'] = self.mutate
# an ordinary quit button for comparison
self.quitButton = Button(self, text='Quit', style='TButton')
self.quitButton.grid(column=0, row=1, sticky=(N,S,E,W))
self.quitButton['command'] = self.quit
def mutate(self):
"""Rotate through the styles by hitting the button."""
style = int(self.mutantButton['style'].split('.')[0])
newStyle = style + 5
if newStyle > 50: newStyle = 10
print('Choosing font '+str(newStyle))
self.mutantButton['style'] = fontStyle[newStyle]
# resize the frame
# get the current geometries
currentGeometry = self._root().geometry()
w, h, x, y = self.parseGeometry(currentGeometry)
reqWidth = self.mutantButton.winfo_reqwidth()
reqHeight = self.mutantButton.winfo_reqheight()
# note assume height of quit button is constant at 20.
w = max([w, reqWidth])
h = 20 + reqHeight
self._root().geometry('%dx%d+%d+%d' % (w, h, x, y))
def parseGeometry(self, geometry):
"""Geometry parser.
Returns the geometry as a (w, h, x, y) tuple."""
# get w
xsplit = geometry.split('x')
w = int(xsplit[0])
rest = xsplit[1]
# get h, x, y
plussplit = rest.split('+')
h = int(plussplit[0])
x = int(plussplit[1])
y = int(plussplit[2])
return w, h, x, y
def resize(self, event):
"""Method bound to the <Configure> event for resizing."""
# get geometry info from the root window.
wm, hm = self._root().winfo_width(), self._root().winfo_height()
# choose a font height to match
# note subtract 30 for the button we are NOT scaling.
# note we assume optimal font height is 1/2 widget height.
fontHeight = (hm - 20) // 2
print('Resizing to font '+str(fontHeight))
# calculate the best font to use (use int rounding)
bestStyle = fontStyle[10] # use min size as the fallback
if fontHeight < 10: pass # the min size
elif fontHeight >= 50: # the max size
bestStyle = fontStyle[50]
else: # everything in between
bestFitFont = (fontHeight // 5) * 5
bestStyle = fontStyle[bestFitFont]
# set the style on the button
self.mutantButton['style'] = bestStyle
root = Tk()
root.title('Alice in Pythonland')
# make a dictionary of sized font styles in the range of interest.
fontStyle = {}
for font in range(10, 51, 5):
styleName = str(font)+'.TButton'
fontName = ' '.join(['helvetica', str(font), 'bold'])
fontStyle[font] = styleName
Style().configure(styleName, font=fontName)
# run the app
app = ButtonApp(master=root)
app.mainloop()
root.destroy()