Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding self-edge in a graphical plot with Python's `daft` library

I want to add an edge that link beta to beta, in the following plot:

enter image description here

Is generated the following code using DAFT:

from matplotlib import rc
rc("font", family="serif", size=12)
rc("text", usetex=True)
import daft

pgm = daft.PGM([2.3, 3.05], origin=[0.3, 0.3], observed_style="inner")

# Hierarchical parameters.
pgm.add_node(daft.Node("beta", r"$\beta$", 1.5, 2))

# Latent variable.
pgm.add_node(daft.Node("w", r"$w_n$", 1, 1))

# Data.
pgm.add_node(daft.Node("x", r"$x_n$", 2, 1, observed=True))

# Add in the edges.
pgm.add_edge("beta", "beta")  # Attempting to create a self-edge, but no effect!
pgm.add_edge("w", "x")
pgm.add_edge("w", "w")
pgm.add_edge("w", "beta")
pgm.add_edge("beta", "x")

# Render and save.
pgm.render()
pgm.figure.savefig("nogray.pdf")

But why it doesn't work? Especially with this line pgm.add_edge("beta", "beta"). I welcome other suggestions other than Daft, as long as it is under Python.

like image 565
neversaint Avatar asked Feb 16 '26 10:02

neversaint


1 Answers

If you look at the source code here from line 301 (the Edge class) you will see that all lines are given by straight lines based on the coordinates ([x, x + dx], [y, y + dy]) as shown below in the code for an undirected edge:

x, y, dx, dy = self._get_coords(ctx)

# Plot the line.
line = ax.plot([x, x + dx], [y, y + dy], **p)
return line 

As such there doesn't appear to be a way of defining a self-edge (as such an edge would need to be curved in order to curve back to the same node).

As far as an alternative library you may want to look at networkx, the following docs show the use with self loops. Alternatively you could raise an issue on the DAFT Github.

like image 156
Ffisegydd Avatar answered Feb 19 '26 00:02

Ffisegydd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!