I am currently in the process of plotting a directed graphs using Julia. After some time on the internet I came across the GraphPLot package which seems to be doing an ok job.
However, I can't find out how to add node labels! Here is my code and output from the jupyter notebook.
Update:
I tried the suggested method from GitHub
nodelabel = [1:number_vertices(g)]
gplot(g, nodelabel = nodelabel)
But I get a weird error:
LoadError: Must have one label per node (or none)
while loading In[44], in expression starting on line 1
Changing
nodelabel = [1:num_vertices(g)]
To nodelabel = collect(1:num_vertices(g)) solves the issue.
Related
I am currently learning Julia and have been practicing in the Jupyter notebook environment. However, the ProgressBar package (similar to TQDM in python) is updated every new line instead of updating on the same line (picture attached). Is there any way to fix this? Thanks.
UPDATE : Here is the full function that I wrote.
function spike_rate(raw_dat, width)
N = size(raw_dat)[1]
domain = collect(1:N);
spike_rat = zeros(N);
for i in ProgressBar(1:N)
dx = i .- domain;
window = gaussian.(dx, width);
spike_rat[i] = sum(window .* raw_dat) ./ width;
end
return spike_rat;
end
This seems to be a known issue with ProgressBars.jl, unfortunately. It's not clear what changed to make these progress bars not work properly anymore, but the maintainer's comment says that tqdm uses "a custom ipywidget" to make this work for the Python library, and that hasn't been implemented for the Julia package yet.
To expand on #Zitzero's mention of ] up, that calls Pkg.update() which also prints a progress bar - so the suggestion is to use the mechanism Pkg uses for it. Pkg has an internal module called MiniProgressBars which handles this output.
Edit: Tim Holy's ProgressMeter package seems well-maintained, and is a much better option than relying on an internal non-exported Pkg submodule with no docs. So I'd recommend ProgressMeter over the below.
The Readme mentions a caveat regarding printing additional information with the progress bar when in Jupyter, which likely applies to MiniProgressBar as well. So, using ProgressMeter, and separating the progress output vs other relevant output to different cells, seems like the best option.
(not recommended)
using Pkg.MiniProgressBars
bar = MiniProgressBar(; indent=2, header = "Progress", color = Base.info_color(),
percentage=false, always_reprint=true)
bar.max = 100
# start_progress(stdout, bar)
for i in 1:100
sleep(0.05) # replace this with your code
# print_progress_bottom(stdout)
bar.current = i
show_progress(stdout, bar)
end
# end_progress(stdout, bar)
This is based on how Pkg uses it, from this file. The commented out lines (with start_progress, print_progress_bottom, and end_progress) are in the original usage in Pkg, but it's not clear what they do and here they just seem to mess up the output - maybe I'm using them wrongly, or maybe Jupyter notebooks only support a subset of the ANSI codes that MiniProgressBars uses.
There is a way, the package module does that as far as I know when you do:
] up
Could you share a little of your code?
For example, where you define what is written to the console.
One guess is that
print("text and progressbar")
instead of
println("text and progressbar")
could help, because println() always creates a new line, while print() should just overwrite you current line.
I am using JuliaPro v0.6.0.1 and the JunoIDE
I tried to apply the DifferentialEquations.jl. In order to run a first example I added the package DifferentialEquations followed by the using statement. In a next step I copied the first example:
f(t,u) = 1.01*u
u0=1/2
tspan = (0.0,1.0)
prob = ODEProblem(f,u0,tspan)
sol = solve(prob,Tsit5(),reltol=1e-8,abstol=1e-8)
using Plots
plot(sol,linewidth=5,title="Solution to the linear ODE with a thick line",
xaxis="Time (t)",yaxis="u(t) (in μm)",label="My Thick Line!") # legend=false
plot!(sol.t, t->0.5*exp(1.01t),lw=3,ls=:dash,label="True Solution!")
Instead of getting the expected graphic I've got the message:
UndefVarError: ODEProblem not defined
Furthermore I've got the warnings right after the: using DifferentialEquations statement
WARNING: The call to compilecache failed to create a usable precompiled cache file for module StochasticDiffEq. Got:
WARNING: Module Iterators uuid did not match cache file.
> LoadError: Declaring __precompile__(true) is only allowed in module files being imported.
which I do not understand. Nevertheless the last warning deals with StochasticDiffEq whereas I'm applying an Ordinary Differential Equation problem.
Any help is appropiated
JuliaPro is incompatible with some packages including DifferentialEquations. I would avoid using JuliaPro and instead use a standard installation until JuliaPro is updated.
I'm unable to save a plot generated by the plot.Node function in data.tree. I've tried the following:
### Create tree object and plot it
data(acme);
plot(acme);
This works fine, showing the plot, as one would expect.
### Try saving it as png
png(filename='file.png', type='cairo-png');
plot(acme);
dev.off();
This creates an empty file. ggsave does the same. Apparantly, plot.Node uses DiagrammeR under the hood, so I looked into that package. It has a function to export graphs:
export_graph(acme, file_name="file.png");
This gives the error:
Error in file.exists(diagram) : invalid 'file' argument
When I transform to GraphViz first, I get a different error:
export_graph(ToGraphViz(acme), file_name="file.png");
Error in graph$dot_code : $ operator is invalid for atomic vectors
Clearly, exporting to GraphViz doesn't quite export to what DiagrammeR expects.
I'm in RStudio and so could in theory just save the plot using the GUI, but I need this for in a script.
Apparently, plot.Node doesn't actually plot anything - instead it seems to generate html/js. Does this mean that that result cannot be stored as a graphic? Or is there some export/conversion function somewhere that I'm completely missing? it certainly feels like I'm missing something obvious - I assume the need to store plotted data.trees as images is quite common. But I have no idea which potential solutions I can still explore.
I'd be very grateful for any pointers anybody has!
As sebastian-c suggested, things work now a bit differently than suggested by Matherion, as of R 3.3.3 with data.tree 0.7.0 and DiagrammeR 0.9.0
Pre-requisite: DiagrmmeRsvg and dependencies need to be installed. Depending on your OS, for this to work you might have to install V8. For example on ubuntu:
apt-get install libv8-3.14-delibv8-3.14-dev
And then in R:
install.packages("DiagrammeRsvg")
On Windows, I didn't have to install anything (maybe because Chrome is installed?).
Once DiagrammeRsvg is available, run:
library(data.tree)
data(acme)
library(DiagrammeR)
export_graph(ToDiagrammeRGraph(acme), "export.pdf")
I've found the answer, at least, partially. There exists a package dedicated to exporting GraphViz diagrams to SVG: DiagrammeRsvg.
So this works:
treeAsSVG <- export_svg(grViz(ToGraphViz(acme)));
writeLines(treeAsSVG, "filename.svg"));
The grViz is necessary to actually convert the ToGRaphViz output to something that can be interpreted by export_svg. I'm still not really sure (yet) what all goes on under the hood - for example, this does not work:
export_graph(grViz(ToGraphViz(acme)), file_name="filename.svg");
But, if anybody else has a similar problem and stumbles upon this question, perhaps this partial answer can help them to at least export something that can then be integrated in e.g. html pages.
By converting acme with as.phylo() it works, but it looks a little boring:
plot(as.phylo(acme),
show.node.label=TRUE,
node.pos=2,
no.margin=TRUE
)
# adding edge labels
edgelabels(as.vector(acme$Get("cost"))[-1],
adj = c(0,-0.5),
frame = "none")
solution with as.phylo()
I also tried as.igraph. However, the nodes overlap and it looks even less pretty:
plot(0, type="n", ann=FALSE, axes=FALSE,
xlim=extendrange(ig[,1]),
ylim=extendrange(ig[,2]))
plot(ig,
layout=layout_as_tree(ig,root=1),
vertex.shape="rectangle",
vertex.size=(strwidth(V(ig)$name) + strwidth("oo")) * 100,
#vertex.size2=strheight("I") * 2 * 100,
edge.label=acme$Get("p",traversal = "level")[-1]
)
solution with as.igraph()
Using Julia 0.3.10 with Juno as IDE and Gadfly latest one. Tried running a sample code, but got stuck with add_plot_element not defined error message. The last line throws the error. Running on Win8 64bit. I'm sure I'm missing something.
using Gadfly
xs = [0:0.1:pi]
k = layer(x=xs, y=sin(xs))
p = plot(x=xs, y=sin(xs))
add_plot_element(k, Guide.title("Now it has a title"))
First, add_plot_element is modifying, so you need the ! like:
add_plot_element!(k,Guide.title(...))
This function is also not exported from Gadfly, so you would really need to write:
Gadfly.add_plot_element!(k, Guide.title("Now it has a title"))
except add_plot_element! doesn't work on Gadfly layers! It does, however, work on plots. What should work:
Gadfly.add_plot_element!(p, Guide.title("Now it has a title"))
since the layer itself doesn't have Guide.Title elements, but the plot does.
I'm currently working through this tutorial and I'm having trouble getting the png image to display. This is my program.
using DataFrames
using Gadfly
train_df = readtable("winequality-red.csv", separator=';')
_, count = hist(train_df["quality"])
class = sort(unique(train_df["quality"]))
value_counts = DataFrame(count=count, class=class)
#value_counts
p = plot(value_counts, x="class", y="count", Geom.bar(), Guide.title("Class distributions (\"quality\")"))
draw(PNG(14cm, 10cm), p)
the error I get is
LoadError("C:/Users/John/Desktop/helloworld.jl",12,MethodError(PNG,(140.0mm,100.0mm)))
I've tried some of the things mentioned in this discussion, however I haven't made any observable progress.
I was able to solve my problem by installing Cairo.
Pkg.add("Cairo")
and changing this line
draw(PNG(14cm, 10cm), p)
to
draw(PNG("chart.png", 14cm, 10cm), p)
and then opening chart.png with Julia Studio