├── LICENSE ├── MANIFEST.in ├── README.rst ├── d3fdgraph ├── __init__.py ├── d3fdgraph.html ├── d3fdgraph.js └── d3fdgraph.py ├── examples └── d3fdgraph_simple_test.ipynb ├── images ├── d3fdgraph_recipes.gif ├── d3fdgraph_recipes.mp4 └── d3fdgraph_recipes.png └── setup.py /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.rst 2 | include d3fdgraph/d3fdgraph.html 3 | include d3fdgraph/d3fdgraph.js 4 | 5 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | d3fdgraph 2 | ========= 3 | 4 | Plots an interactive force directed graph in a jupyter notebook, taking data from a dataframe of nodes and link weights. 5 | 6 | 7 | Why d3fdgraph? 8 | -------------- 9 | 10 | Working with data using **python** in the **jupyter** notebook provides many options for visualising that data. 11 | 12 | The **pandas** library provides convenient common visualisations, and there's always the venerable **matplotlib** for more bespoke plots. The new **vega-lite** library is enabled by default in jupyterlab. 13 | 14 | Sometimes we want to plot the relationships between things as a graph of linked nodes. 15 | 16 | The **networkx** library can plot graphs in a notebook but the plots are static, and only really suitable for smaller data. 17 | 18 | Being able to **interactively** adjust graphs really helps explore larger data. 19 | 20 | That's what **d3fdgraph** does. 21 | 22 | 23 | Installing d3fdgraph 24 | -------------------- 25 | 26 | Installing **d3fdgraph** is easy. 27 | :: 28 | 29 | pip install d3fdgraph 30 | 31 | This has been tested with Anaconda Python 3. 32 | 33 | 34 | How To Use 35 | ---------- 36 | 37 | To use **d3fdgraph** in a notebook we import the library. 38 | :: 39 | 40 | import d3fdgraph 41 | 42 | 43 | **d3fdgraph** takes data in the form of a **pandas dataframe**. 44 | 45 | That dataframe must have 3 columns: 46 | 47 | * The first column contains the nodes at the **start** of a link. 48 | 49 | * The second column contains the nodes at the **end** of a link. 50 | 51 | * The third column contains a link **weight** number. It must be more than 0. 52 | 53 | The larger the **weight**, the more strongly related the two nodes at each end of this link. 54 | 55 | Here is an example dataframe: 56 | 57 | ======= ======= ======== 58 | source target weight 59 | ======= ======= ======== 60 | apple orange 1 61 | apple banana 2 62 | orange mango 2 63 | orange lemon 3 64 | ======= ======= ======== 65 | 66 | Each row is a link: 67 | 68 | * The first row is a link between ``apple`` and ``orange``. These two are connected with a weight of 1. 69 | * The second row is a link between ``apple`` and ``banana``. These two are more strongly related, with a weight 2. 70 | * The fourth row is the strongest link, with weight 3, between ``orange`` and ``lemon``. 71 | 72 | The column names don't have to be ``source``, ``target`` and ``weight``. You can have different column names, but it is a good idea to use descriptive names. 73 | 74 | The order of the 3 columns is what matters. **d3fdgraph** will use the first column as the source nodes, the second as the target, and the third as link weights. 75 | 76 | To draw an interactive force directed graph of these nodes and links we simply pass this dataframe to the **plot_force_directed_graph()** function. 77 | :: 78 | 79 | d3fdgraph.plot_force_directed_graph(dataframe) 80 | 81 | Here is an example of a graph made from different data. 82 | 83 | .. image:: https://github.com/intuitivetextmining/d3fdgraph/blob/master/images/d3fdgraph_recipes.gif 84 | 85 | The nodes are labelled with the names of the nodes, as described in the pandas dataframe. 86 | 87 | The nodes are constrained from flying off the edge of the canvas. 88 | 89 | 90 | Interactivity 91 | ------------- 92 | 93 | You can use your pointer to drag nodes around to adjust the graph. 94 | 95 | Double-clicking a node makes it jump to the centre of the canvas, from where it might depart slightly due to the simulated forces. 96 | 97 | 98 | Additional Parameters 99 | --------------------- 100 | 101 | :: 102 | 103 | plot_force_directed_graph(node1_node1_weight, node_radius=3, link_distance=20, collision_scale=4) 104 | 105 | You don't have to use the additional parameters, but they might help improve the readability of your graph. 106 | 107 | * **node_radius** is the radius of the circles drawn for each node, default 3 108 | * **link_distance** is the length of each link, before divided by the link weight, default 20 109 | * **collision_scale** is the multiple of the node radius that excludes other nodes, default 4 110 | * **link_width_scale** scales the width of the drawn links with link weight, default is 4 111 | 112 | 113 | Example Notebook 114 | ---------------- 115 | A simple jupyter notebook showing how **d3fdgraph** can be used is here: 116 | 117 | * `simple example notebook `_ 118 | 119 | 120 | Note 121 | ---- 122 | 123 | Note that **d3fdgraph** is only useful in a jupyter notebook. It isn't useful in a terminal, and hasn't been tested in other kinds of python notebook. 124 | 125 | **d3graph** has been tested to work in the Anaconda Python's jupyter notebook, and also the mybinder instances too. Recently it has been made to work in Google's Colab notebook environment. 126 | 127 | **JupyterLab** is moving away from allowing javascript in notebook cells, and encouraging develpment of extensions insted. Since JupyterLab is not ready for production, and not widely adopted yet, the focus here is on Jupyter and Colab notebooks. 128 | -------------------------------------------------------------------------------- /d3fdgraph/__init__.py: -------------------------------------------------------------------------------- 1 | from .d3fdgraph import plot_force_directed_graph -------------------------------------------------------------------------------- /d3fdgraph/d3fdgraph.html: -------------------------------------------------------------------------------- 1 | 2 |
3 |
force-directed graph
4 | 5 | -------------------------------------------------------------------------------- /d3fdgraph/d3fdgraph.js: -------------------------------------------------------------------------------- 1 | // require is how jupyter manages javascript libraries 2 | require.config({ 3 | paths: { 4 | d3: 'https://d3js.org/d3.v5.min' 5 | } 6 | }); 7 | 8 | require(["d3"], function(d3) { 9 | //console.log(d3.version); 10 | 11 | // size of plot 12 | const width = 800; 13 | const height = 600; 14 | 15 | // node radius 16 | const node_radius = %%noderadius%%; 17 | // link distance before weight is applied 18 | const link_distance = %%linkdistance%%; 19 | // collision exclusion sclae 20 | const collision_scale = %%collisionscale%%; 21 | // link with scale 22 | const link_width_scale = %%linkwidthscale%%; 23 | 24 | // links and nodes data 25 | const links = %%links%%; 26 | const nodes = %%nodes%%; 27 | 28 | 29 | // create simulation 30 | const simulation = d3.forceSimulation(nodes) 31 | .force("link", d3.forceLink(links).id(d => d.id).distance(d => link_distance / d.%%edge_attribute%%)) 32 | .force("charge", d3.forceManyBody().strength(-20)) 33 | .force('collision', d3.forceCollide().radius(collision_scale * node_radius)) 34 | .force("center", d3.forceCenter(width / 2, height / 2)); 35 | 36 | /// dragging nodes 37 | const drag = simulation => { 38 | 39 | function dragstarted(d) { 40 | if (!d3.event.active) simulation.alphaTarget(0.3).restart(); 41 | d.fx = d.x; 42 | d.fy = d.y; 43 | } 44 | 45 | function dragged(d) { 46 | d.fx = d3.event.x; 47 | d.fy = d3.event.y; 48 | } 49 | 50 | function dragended(d) { 51 | if (!d3.event.active) simulation.alphaTarget(0); 52 | d.fx = null; 53 | d.fy = null; 54 | } 55 | 56 | return d3.drag() 57 | .on("start", dragstarted) 58 | .on("drag", dragged) 59 | .on("end", dragended); 60 | } 61 | 62 | // select HTML element and attach SVG to it 63 | const svg = d3.select("#d3-container-%%unique-id%%") 64 | .append("svg") 65 | .attr("width", width) 66 | .attr("height", height); 67 | 68 | // add links to svg element 69 | const link = svg.append("g") 70 | .attr("class", "links") 71 | .selectAll("line") 72 | .data(links) 73 | .enter().append("line") 74 | .style("stroke-width", d => Math.sqrt(link_width_scale*d.%%edge_attribute%%)); 75 | 76 | const node = svg.append("g") 77 | .attr("class", "nodes") 78 | .selectAll("g") 79 | .data(nodes) 80 | .enter().append("g"); 81 | 82 | 83 | const circle = node.append("circle") 84 | .attr("r", node_radius) 85 | .on("dblclick", d => {d.x = width/2; d.y = height/2;}) 86 | .call(drag(simulation)); 87 | 88 | // svg text labels for eachnode 89 | const label = node.append("text") 90 | .attr("dx", 10) 91 | .attr("dy", ".35em") 92 | .text(d => d.id); 93 | 94 | 95 | // update svg on simulation ticks 96 | simulation.on("tick", () => { 97 | circle 98 | // keep within edge of canvas, larger margin on right for text labels 99 | .attr("cx", d => (d.x = Math.max(2*node_radius, Math.min(width - 2*node_radius - 10*d.id.length, d.x)) )) 100 | .attr("cy", d => (d.y = Math.max(2*node_radius, Math.min(height - 2*node_radius, d.y)) )); 101 | 102 | link 103 | .attr("x1", d => d.source.x) 104 | .attr("y1", d => d.source.y) 105 | .attr("x2", d => d.target.x) 106 | .attr("y2", d => d.target.y); 107 | 108 | 109 | label 110 | .attr("x", d => d.x) 111 | .attr("y", d => d.y); 112 | }); 113 | 114 | 115 | //return svg.node(); 116 | 117 | }); 118 | 119 | -------------------------------------------------------------------------------- /d3fdgraph/d3fdgraph.py: -------------------------------------------------------------------------------- 1 | import IPython.core.display 2 | import pkg_resources 3 | 4 | import networkx 5 | import networkx.readwrite.json_graph 6 | 7 | import random 8 | 9 | 10 | def plot_force_directed_graph(node1_node1_weight, node_radius=3, link_distance=20, collision_scale=4, link_width_scale=4): 11 | 12 | # column names for node source and target, and edge attributes 13 | node_source_name = node1_node1_weight.columns.values[0] 14 | node_target_name = node1_node1_weight.columns.values[1] 15 | link_edge_name = node1_node1_weight.columns.values[2] 16 | 17 | # convert node1_node1_weight to graph 18 | graph = networkx.from_pandas_edgelist(node1_node1_weight, source=node_source_name, target=node_target_name, edge_attr=link_edge_name) 19 | 20 | # convert graph nodes and inks to json, ready for d3 21 | graph_json = networkx.readwrite.json_graph.node_link_data(graph) 22 | graph_json_nodes = graph_json['nodes'] 23 | graph_json_links = graph_json['links'] 24 | 25 | 26 | # load html and javascript from template files 27 | resource_package = __name__ 28 | html_template = 'd3fdgraph.html' 29 | html = pkg_resources.resource_string(resource_package, html_template).decode('utf-8') 30 | javascript_template = 'd3fdgraph.js' 31 | js_code = pkg_resources.resource_string(resource_package, javascript_template).decode('utf-8') 32 | 33 | # generate random identifier for SVG element, to avoid name clashes if used multiple times in a notebook 34 | random_id_string = str(random.randrange(1000000,9999999)) 35 | # replace placeholder in both html and js templates 36 | html = html.replace('%%unique-id%%', random_id_string) 37 | js_code = js_code.replace('%%unique-id%%', random_id_string) 38 | 39 | # substitute configuration values 40 | js_code = js_code.replace('%%noderadius%%', str(node_radius)) 41 | js_code = js_code.replace('%%linkdistance%%', str(link_distance)) 42 | js_code = js_code.replace('%%collisionscale%%', str(collision_scale)) 43 | js_code = js_code.replace('%%linkwidthscale%%', str(link_width_scale)) 44 | 45 | # substitute links and data 46 | js_code = js_code.replace('%%links%%', str(graph_json_links)) 47 | js_code = js_code.replace('%%nodes%%', str(graph_json_nodes)) 48 | js_code = js_code.replace('%%edge_attribute%%', link_edge_name) 49 | 50 | # display html in notebook cell 51 | IPython.core.display.display_html(IPython.core.display.HTML(html)) 52 | 53 | # display (run) javascript in notebook cell 54 | IPython.core.display.display_javascript(IPython.core.display.Javascript(data=js_code)) 55 | pass -------------------------------------------------------------------------------- /examples/d3fdgraph_simple_test.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "simple notebook showing how **d3fdgraph** is used." 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "# import the d3fdgraph and pandas libraries\n", 17 | "\n", 18 | "import d3fdgraph\n", 19 | "import pandas" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": 3, 25 | "metadata": {}, 26 | "outputs": [], 27 | "source": [ 28 | "# create a pandas data frame\n", 29 | "\n", 30 | "df = pandas.DataFrame(\n", 31 | " [{\"source\": \"apple\", \"target\": \"banana\", \"weight\": 1},\n", 32 | " {\"source\": \"apple\", \"target\": \"orange\", \"weight\": 2},\n", 33 | " {\"source\": \"banana\", \"target\": \"orange\", \"weight\":3},\n", 34 | " {\"source\": \"orange\", \"target\": \"mango\", \"weight\":3},\n", 35 | " {\"source\": \"mango\", \"target\": \"plum\", \"weight\":3},\n", 36 | " {\"source\": \"kiwi\", \"target\": \"grape\", \"weight\":3}\n", 37 | " ])" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": 4, 43 | "metadata": {}, 44 | "outputs": [ 45 | { 46 | "data": { 47 | "text/html": [ 48 | "
\n", 49 | "\n", 62 | "\n", 63 | " \n", 64 | " \n", 65 | " \n", 66 | " \n", 67 | " \n", 68 | " \n", 69 | " \n", 70 | " \n", 71 | " \n", 72 | " \n", 73 | " \n", 74 | " \n", 75 | " \n", 76 | " \n", 77 | " \n", 78 | " \n", 79 | " \n", 80 | " \n", 81 | " \n", 82 | " \n", 83 | " \n", 84 | " \n", 85 | " \n", 86 | " \n", 87 | " \n", 88 | " \n", 89 | " \n", 90 | " \n", 91 | " \n", 92 | " \n", 93 | " \n", 94 | " \n", 95 | " \n", 96 | " \n", 97 | " \n", 98 | " \n", 99 | " \n", 100 | " \n", 101 | " \n", 102 | " \n", 103 | " \n", 104 | " \n", 105 | " \n", 106 | " \n", 107 | " \n", 108 | " \n", 109 | "
sourcetargetweight
0applebanana1
1appleorange2
2bananaorange3
3orangemango3
4mangoplum3
5kiwigrape3
\n", 110 | "
" 111 | ], 112 | "text/plain": [ 113 | " source target weight\n", 114 | "0 apple banana 1\n", 115 | "1 apple orange 2\n", 116 | "2 banana orange 3\n", 117 | "3 orange mango 3\n", 118 | "4 mango plum 3\n", 119 | "5 kiwi grape 3" 120 | ] 121 | }, 122 | "execution_count": 4, 123 | "metadata": {}, 124 | "output_type": "execute_result" 125 | } 126 | ], 127 | "source": [ 128 | "# show the dataframe of nodes and link weights\n", 129 | "\n", 130 | "df" 131 | ] 132 | }, 133 | { 134 | "cell_type": "code", 135 | "execution_count": 5, 136 | "metadata": { 137 | "scrolled": false 138 | }, 139 | "outputs": [ 140 | { 141 | "data": { 142 | "text/html": [ 143 | "
\n", 144 | "
force-directed graph
\n", 145 | "\n", 146 | "" 165 | ] 166 | }, 167 | "metadata": {}, 168 | "output_type": "display_data" 169 | }, 170 | { 171 | "data": { 172 | "application/javascript": [ 173 | "// require is how jupyter manages javascript libraries\n", 174 | "require.config({\n", 175 | " paths: {\n", 176 | " d3: 'https://d3js.org/d3.v5.min'\n", 177 | " }\n", 178 | "});\n", 179 | "\n", 180 | "require([\"d3\"], function(d3) {\n", 181 | " //console.log(d3.version);\n", 182 | "\n", 183 | " // size of plot\n", 184 | " const width = 800;\n", 185 | " const height = 600;\n", 186 | "\n", 187 | " // node radius\n", 188 | " const radius = 4.5;\n", 189 | "\n", 190 | " // links and nodes data\n", 191 | " const links = [{'weight': 1, 'source': 'apple', 'target': 'banana'}, {'weight': 2, 'source': 'apple', 'target': 'orange'}, {'weight': 3, 'source': 'banana', 'target': 'orange'}, {'weight': 3, 'source': 'orange', 'target': 'mango'}, {'weight': 3, 'source': 'mango', 'target': 'plum'}, {'weight': 3, 'source': 'kiwi', 'target': 'grape'}];\n", 192 | " const nodes = [{'id': 'apple'}, {'id': 'banana'}, {'id': 'orange'}, {'id': 'mango'}, {'id': 'plum'}, {'id': 'kiwi'}, {'id': 'grape'}];\n", 193 | "\n", 194 | "\n", 195 | " // create simulation\n", 196 | " const simulation = d3.forceSimulation(nodes)\n", 197 | " .force(\"link\", d3.forceLink(links).id(d => d.id).distance(d => 10 / d.weight))\n", 198 | " .force(\"charge\", d3.forceManyBody())\n", 199 | " .force(\"center\", d3.forceCenter(width / 2, height / 2));\n", 200 | "\n", 201 | " /// dragging nodes\n", 202 | " const drag = simulation => {\n", 203 | "\n", 204 | " function dragstarted(d) {\n", 205 | " if (!d3.event.active) simulation.alphaTarget(0.3).restart();\n", 206 | " d.fx = d.x;\n", 207 | " d.fy = d.y;\n", 208 | " }\n", 209 | "\n", 210 | " function dragged(d) {\n", 211 | " d.fx = d3.event.x;\n", 212 | " d.fy = d3.event.y;\n", 213 | " }\n", 214 | "\n", 215 | " function dragended(d) {\n", 216 | " if (!d3.event.active) simulation.alphaTarget(0);\n", 217 | " d.fx = null;\n", 218 | " d.fy = null;\n", 219 | " }\n", 220 | "\n", 221 | " return d3.drag()\n", 222 | " .on(\"start\", dragstarted)\n", 223 | " .on(\"drag\", dragged)\n", 224 | " .on(\"end\", dragended);\n", 225 | " }\n", 226 | "\n", 227 | " // select HTML element and attach SVG to it\n", 228 | " const svg = d3.select(\"#d3-container-4286987\")\n", 229 | " .append(\"svg\")\n", 230 | " .attr(\"width\", width)\n", 231 | " .attr(\"height\", height);\n", 232 | "\n", 233 | " // add links to svg element\n", 234 | " const link = svg.append(\"g\")\n", 235 | " .attr(\"class\", \"links\")\n", 236 | " .selectAll(\"line\")\n", 237 | " .data(links)\n", 238 | " .enter().append(\"line\")\n", 239 | " .attr(\"stroke-width\", d => Math.sqrt(d.weight));\n", 240 | "\n", 241 | " const node = svg.append(\"g\")\n", 242 | " .attr(\"class\", \"nodes\")\n", 243 | " .selectAll(\"g\")\n", 244 | " .data(nodes)\n", 245 | " .enter().append(\"g\");\n", 246 | "\n", 247 | "\n", 248 | " const circle = node.append(\"circle\")\n", 249 | " .attr(\"r\", radius)\n", 250 | " .on(\"dblclick\", d => {d.x = width/2; d.y = height/2;})\n", 251 | " .call(drag(simulation));\n", 252 | "\n", 253 | " // svg text labels for eachnode\n", 254 | " const label = node.append(\"text\")\n", 255 | " .attr(\"dx\", 10)\n", 256 | " .attr(\"dy\", \".35em\")\n", 257 | " .text(d => d.id);\n", 258 | "\n", 259 | "\n", 260 | " // update svg on simulation ticks\n", 261 | " simulation.on(\"tick\", () => {\n", 262 | " circle\n", 263 | " // keep within edge of canvas, larger margin on right for text labels\n", 264 | " .attr(\"cx\", d => (d.x = Math.max(2*radius, Math.min(width - 10*radius, d.x)) ))\n", 265 | " .attr(\"cy\", d => (d.y = Math.max(2*radius, Math.min(width - 10*radius, d.y)) ));\n", 266 | "\n", 267 | " link\n", 268 | " .attr(\"x1\", d => d.source.x)\n", 269 | " .attr(\"y1\", d => d.source.y)\n", 270 | " .attr(\"x2\", d => d.target.x)\n", 271 | " .attr(\"y2\", d => d.target.y);\n", 272 | "\n", 273 | "\n", 274 | " label\n", 275 | " .attr(\"x\", d => d.x)\n", 276 | " .attr(\"y\", d => d.y);\n", 277 | " });\n", 278 | "\n", 279 | "\n", 280 | " //return svg.node();\n", 281 | "\n", 282 | "});\n", 283 | "\n" 284 | ] 285 | }, 286 | "metadata": {}, 287 | "output_type": "display_data" 288 | } 289 | ], 290 | "source": [ 291 | "# plot interactive force directed graph of linked nodes\n", 292 | "# use pointer to grab and move nodes to adjust the graph\n", 293 | "\n", 294 | "d3fdgraph.plot_force_directed_graph(df)" 295 | ] 296 | }, 297 | { 298 | "cell_type": "code", 299 | "execution_count": null, 300 | "metadata": {}, 301 | "outputs": [], 302 | "source": [] 303 | } 304 | ], 305 | "metadata": { 306 | "kernelspec": { 307 | "display_name": "Python 3", 308 | "language": "python", 309 | "name": "python3" 310 | }, 311 | "language_info": { 312 | "codemirror_mode": { 313 | "name": "ipython", 314 | "version": 3 315 | }, 316 | "file_extension": ".py", 317 | "mimetype": "text/x-python", 318 | "name": "python", 319 | "nbconvert_exporter": "python", 320 | "pygments_lexer": "ipython3", 321 | "version": "3.7.1" 322 | } 323 | }, 324 | "nbformat": 4, 325 | "nbformat_minor": 2 326 | } 327 | -------------------------------------------------------------------------------- /images/d3fdgraph_recipes.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/intuitivetextmining/d3fdgraph/95bf77a2d7f1c4031932df19886c5f3e5882e837/images/d3fdgraph_recipes.gif -------------------------------------------------------------------------------- /images/d3fdgraph_recipes.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/intuitivetextmining/d3fdgraph/95bf77a2d7f1c4031932df19886c5f3e5882e837/images/d3fdgraph_recipes.mp4 -------------------------------------------------------------------------------- /images/d3fdgraph_recipes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/intuitivetextmining/d3fdgraph/95bf77a2d7f1c4031932df19886c5f3e5882e837/images/d3fdgraph_recipes.png -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import pathlib 2 | from setuptools import setup 3 | 4 | # The directory containing this file 5 | HERE = pathlib.Path(__file__).parent 6 | 7 | # The text of the README file 8 | README = (HERE / "README.rst").read_text() 9 | 10 | setup(name='d3fdgraph', 11 | version='0.34', 12 | description='Interactive force-directed graph in a jupyter notebook.', 13 | long_description=README, 14 | long_description_content_type="text/x-rst", 15 | url='https://github.com/intuitivetextmining/d3fdgraph', 16 | author='Intuitive Text Mining', 17 | author_email='intuitivetextmining@gmail.com', 18 | license='GPLv2', 19 | packages=['d3fdgraph'], 20 | install_requires=['IPython', 'networkx', 'networkx'], 21 | include_package_data=True, 22 | zip_safe=False) --------------------------------------------------------------------------------