daft-dev / daft

Render probabilistic graphical models using matplotlib
https://docs.daft-pgm.org
MIT License
675 stars 118 forks source link

overlay graph on image? #64

Closed JohnGriffiths closed 5 years ago

JohnGriffiths commented 10 years ago

Hi.

Could I ask for a basic example of how I might overlay a daft graph on an image?

(context = I'm making a diagram of a small network of brain regions; an image in the background would be v. handy for visual interpretation)

I'm expecting/hoping that the matplotlib base should make this more straightforward than e.g. with graphviz.

Ta.

JohnGriffiths commented 10 years ago

Anyone any thoughts on this?

dsfulf commented 5 years ago

Here's an example of getting the current axis after pgm.render() and adding an additional artist or primitive.

import matplotlib.pyplot as plt
import daft

pgm = daft.PGM(grid_unit=2.5, node_unit=2)

pgm.add_node(node='bias', content=r'$x_{0}$', x=0, y=1, fontsize=16, plot_params=dict(ec='C1'))
pgm.add_node(node='parameter', content=r'$x_{1}$', x=0, y=0, fontsize=16, plot_params=dict(ec='C1'))
pgm.add_node(node='output', content=r'$y$', x=2, y=.5, fontsize=16, plot_params=dict(ec='C0'))

pgm.add_edge(name1='bias', name2='output', plot_params=dict(ec='C0',  lw=2))
pgm.add_edge(name1='parameter', name2='output', plot_params=dict(ec='C0', lw=2))

pgm.render()

ax = plt.gcf().gca()
ax.annotate(r'$w_0$', xy=[3.3, 3.1], fontsize=16, backgroundcolor='white', rotation=-10)
ax.annotate(r'$w_1$', xy=[3.3, 1.75], fontsize=16, backgroundcolor='white', rotation=10)

ax.annotate(r'$y = \sum_{i=0}^{n}x_i w_i + \hat{e}$', xy=[7, 4.25], fontsize=16)

plt.gcf().subplots_adjust(right=1)

plt.savefig('nn_lr.png', dpi=100, bbox_inches='tight')

nn_lr