beeware / toga-chart

A matplotlib charting widget for Toga.
BSD 3-Clause "New" or "Revised" License
27 stars 12 forks source link

Providing Example for networkx #80

Open buddha314 opened 10 months ago

buddha314 commented 10 months ago

What is the problem or limitation you are having?

Networkx is a powerful tool in data analysis, would be nice to see an example

Describe the solution you'd like

I'm providing code here for a basic example. It should be pointed out that most networkx examples rely on the plot.show() command which does not appear to be available in toga-chart. So you have to do the drawing yourself. That's okay, networks still provides the layout.

    """This is where the chart is created"""
    def draw_chart(self, chart, figure, *args, **kwargs):
        # The Karate Club example is built into nx
        G = nx.karate_club_graph()
        ax = figure.add_subplot(1, 1, 1)
        ax.set_axis_off()
        pos = nx.circular_layout(G)
       # Spring is a more popular layout, but circular is easier to debug
        #pos = nx.spring_layout(G)
        x = [k[0] for k in pos.values()]
        y = [k[1] for k in pos.values()]
        for e in G.edges():
            # Note, this takes a sequence of xs, then ys.  That took a while!
            p1 = [x[e[0]], x[e[1]]]
            p2 = [y[e[0]], y[e[1]]]
            ax.plot(p1, p2, marker='o', linestyle='-', color='r')

Describe alternatives you've considered

Tried matplotlib directly.

Additional context

Hoping this is useful to someone.

freakboy3742 commented 10 months ago

Thanks for the suggestion. I don't want Toga-chart's documentation to become a reproduction of all of Matplotlib's documentation (or an attempt at a replacement for Matplotlib's documentation) - but a couple of examples showing how Matplotlib code maps to Toga-chart is definitely called for - especially when it comes to core usage issues like the fact that plot.show() isn't explicitly needed. Tagging as a documentation ticket on that basis.