Accessing backend specific functionality with Julia Plots - matplotlib

Plots is simple and powerful but sometimes I would like to have a little bit more control over individual elements of the plot to fine-tune its appearance.
Is it possible to update the plot object of the backend directly?
E.g., for the default pyplot backend, I tried
using Plots
p = plot(sin)
p.o[:axes][1][:xaxis][:set_ticks_position]("top")
but the plot does not change. Calling p.o[:show]() afterwards does not help, either.
In other words: Is there a way to use the PyPlot interface for a plot that was initially created with Plots?
Edit:
The changes to the PyPlot object become visible (also in the gui) when saving the figure:
using Plots
using PyPlot
p = Plots.plot(sin, top_margin=1cm)
gui() # not needed when using the REPL
gca()[:xaxis][:set_ticks_position]("top")
PyPlot.savefig("test.png")
Here, I used p.o[:axes][1] == gca(). One has to set top_margin=1cm because the plot area is not adjusted automatically (for my actual fine-tuning, this doesn't matter).
This also works for subsequent updates as long as only the PyPlot interface is used. E.g., after the following commands, the plot will have a red right border in addition to labels at the top:
gca()[:spines]["right"][:set_color]("red")
PyPlot.savefig("test.png")
However, when a Plots command like plot!(xlabel="foo") is used, all previous changes made with PyPlot are overwritten (which is not suprising).
The remaining question is how to update the gui interactively without having to call PyPlot.savefig explicitly.

No - the plot is a Plots object, not a PyPlot object. In your specific example you can do plot(sin, xmirror = true).

I'm trying to do the same but didn't find a solution to update an existing plot. But here is a partial answer: you can query information from the PyPlot axes object
julia> Plots.plot(sin, 1:4)
julia> Plots.PyPlot.plt[:xlim]()
(1.0,4.0)
julia> Plots.plot(sin, 20:24)
julia> ax = Plots.PyPlot.plt[:xlim]()
(20.0,24.0)
and it gets updated.

Related

Matplotlib widget, secondary y axis, twinx

i use jupyterlab together with matplotlib widgets. I have ipywidgets installed.
My goal is to choose which y-axis data is displayed in the bottom of the figure.
When i use the interactive tool to see the coordinates i get only the data of the right y-axis displayed. Both would be really nice^^ My minimal code example:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib widgets
x=np.linspace(0,100)
y=x**2
y2=x**3
fig,ax=plt.subplots()
ax2=ax.twinx()
ax.plot(x,y)
ax2.plot(x,y2)
plt.show()
With this example you might ask why not to plot them to the same y-axis but thats why it is a minimal example. I would like to plot data of different units.
To choose which y-axis is used, you can set the zorder property of the axes containing this y-axis to a higher value than that of the other axes (0 is the default):
ax.zorder = 1
However, that will cause this Axes to obscure the other Axes. To counteract this, use
ax.set_facecolor((0, 0, 0, 0))
to make the background color of this Axes transparent.
Alternatively, use the grab_mouse function of the figure canvas:
fig.canvas.grab_mouse(ax)
See here for the (minimal) documentation for grab_mouse.
The reason this works is this:
The coordinate line shown below the figure is obtained by an event callback which ultimately calls matplotlib.Axes.format_coord() on the axes instance returned by the inaxes property of the matplotlib events that are being generated by your mouse movement. This Axes is the one returned by FigureCanvasBase.inaxes() which uses the Axes zorder, and in case of ties, chooses the last Axes created.
However, you can tell the figure canvas that one Axes should receive all mouse events, in which case this Axes is also set as the inaxes property of generated events (see the code).
I have not found a clean way to make the display show data from both Axes. The only solution I have found would be to monkey-patch NavigationToolbar2._mouse_event_to_message (also here) to do what you want.

save pyplot figure "as figure" (not as image)

How can I save a figure using PyPlot in Julia, so that the figure can be reloaded as a figure later in Julia? (not as an image)
You can use serialize to store any Julia object. This beautifully works for plots as well.
Let us start by generating a plot:
using Plots
pyplot()
p = plot(rand(10));
using Serialization
Serialization.serialize("myfile.jld", p);
Note that you need a semicolon after plot command so it does not appear on the screen.
Let us now read the plot (to have a full test I ended the previous Julia session and started a new one):
using Plots
pyplot();
using Serialization
p2 = Serialization.deserialize("myfile.jld");
In order to display it now it is enough to type in REPL:
julia> p2
You might want also want to use plain PyPlot (I strongly recommend Plots for flexibility). In that case your best bet is to follow rules described in object-oriented API of Matplotlib:
using PyPlot
ioff()
fig = subplot()
fig.plot(rand(10))
fig.set_title("Hello world")
using Serialization
serialize("pp.jld", fig)
In order to plot de-serialize back the object:
using PyPlot
ioff()
using Serialization
fig = deserialize("pp.jld")
show()
Finally, note that the serialization is good only for short term storage. If anything changes (e.g. you update Julia packages) you might not be able to de-serialize the plot.
Hence another good alternative for processable plots are saving them to LaTeX or SVG format - both is possible in Julia.

Draw an ordinary plot with the same style as in plt.hist(histtype='step')

The method plt.hist() in pyplot has a way to create a 'step-like' plot style when calling
plt.hist(data, histtype='step')
but the 'ordinary' methods that plot raw data without processing (plt.plot(), plt.scatter(), etc.) apparently do not have style options to obtain the same result. My goal is to plot a given set of points using that style, without making histogram of these points.
Is that achievable with standard library methods for plotting a given 2-D set of points?
I also think that there is at least one hack (generating a fake distribution which would have histogram equal to our data) and a 'low-level' solution to draw each segment manually, but none of these ways seems favorable.
Maybe you are looking for drawstyle="steps".
import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
data = np.cumsum(np.random.randn(10))
plt.plot(data, drawstyle="steps")
plt.show()
Note that this is slightly different from histograms, because the lines do not go to zero at the ends.

Generating subplots of heatmaps in Julia-lang

I am trying to produce a figure/plot with more than a single heatmap (matrix with color shading according to the cell value). At the moment using Plots;
pyplot() and heatmap(mat) is enough to produce a heatmap.
It is not clear to me how to produce a single figure with more though. After looking at this page example subplots for how to use the layout, and then the example histogram, I cannot seem to produce working examples for the two together.
The question is how to produce a figure with two different matrices displayed via heatmap or some other function to do the same?
(as an extra side, could you also explain the context of the 'using' statement and how it relates to the 'backend'?)
The easiest way is to make a Vector of heatmaps, then plot those
using Plots
hms = [heatmap(randn(10,10)) for i in 1:16];
plot(hms..., layout = (4,4), colorbar = false)
The using statement calls the Plots library. The "backend" is another package, loaded by Plots, that does the actual plotting. Plots itself has no plotting capabilities - it translates the plot call to a plot call for the backend package.
Explanation of the code above:
Plotting with Plots is a two-step process. 1: plot generates a Plot object with all the information for the plot; 2: when a Plot object is returned to the console, it automatically calls julia´s display function, which then generates the plot. But you can do other things with the Plot object first, like put it in an array.
The heatmap call is a short form of plot(randn(10,10), seriestype = :heatmap), so it just creates a Plot object. 16 Plot objects are stored in the vector.
Passing a number of Plot objects to plot creates a new, larger Plot, with each of the incoming Plot objects as subplots. The splat operator ... simply passes each element of the Array{Plot} to plot as an individual argument.

Gridlines in Julia PyPlot

I'm using the "PyPlot" package in Julia, and I want to add gridlines at specified locations. I'm not familiar enough with Python/Matlab to use their documentation pages to help - the commands differ in Julia. I want a basic plot, with gridlines on both axes at intervals of 1:
using PyPlot
fig=figure("Name")
grid("on")
scatter([1,2,3,4],[4,5,6,7])
Help appreciated...
PyPlot is just an interface to Matplotlib, so the commands
to customize the grid are Matplotlib's commands.
One way to configure the gridlines on both axes at intervals of 1 (for the given data) is:
using PyPlot
fig=figure(figsize=[6,3])
ax1=subplot(1,1,1) # creates a subplot with just one graphic
ax1[:xaxis][:set_ticks](collect(1:4)) # configure x ticks from 1 to 4
ax1[:yaxis][:set_ticks](collect(4:7)) # configure y ticks from 4 to 7
grid("on")
scatter([1,2,3,4],[4,5,6,7])
This code was tested inside an IJulia's notebook, and produces the following output:
Take a look at Various Julia plotting examples using PyPlot.
tested with Julia Version 0.4.3
The values where grid lines are drawn can be controlled by passing an array to the xticks() and yticks() functions.
A simple example:
using PyPlot
fig=figure("Name")
grid("on")
xticks(0:5)
yticks(3:8)
scatter([1,2,3,4],[4,5,6,7])
If you want it to be more flexible you can figure out the limits based on your data and set the tick interval to something else.
One little more dynamic way to configure the x-axis of the grid could be:
x_data = [1,2,3,4]
x_tick_interval = 2;
x_tick_start = minimum(xdata)
x_tick_end = maximum(xdata)
xticks(x_tick_start:x_tick_interval:x_tick_end)