tips for creating Graph diagrams

后端 未结 3 1281
感情败类
感情败类 2020-12-14 10:53

I\'d like to programmatically create diagrams like this
(source: yaroslavvb.com)

I imagine I should use GraphPlot with VertexCoordinateRules, Verte

3条回答
  •  轮回少年
    2020-12-14 11:06

    Generalising Samsdram's answer a bit, I get

    GraphPlotHighlight[edges:{((_->_)|{_->_,_})..},hl:{___}:{},opts:OptionsPattern[]]:=Module[{verts,coords,g,sub},
      verts=Flatten[edges/.Rule->List]//.{a___,b_,c___,b_,d___}:>{a,b,c,d};
      g=GraphPlot[edges,FilterRules[{opts}, Options[GraphPlot]]];
      coords=VertexCoordinateRules/.Cases[g,HoldPattern[VertexCoordinateRules->_],2];
      sub=Flatten[Position[verts,_?(MemberQ[hl,#]&)]];
      coords=coords[[sub]];     
      Show[Graphics[{OptionValue[HighlightColor],CapForm["Round"],JoinForm["Round"],Thickness[OptionValue[HighlightThickness]],Line[AppendTo[coords,First[coords]]],Polygon[coords]}],g]
    ]
    Protect[HighlightColor,HighlightThickness];
    Options[GraphPlotHighlight]=Join[Options[GraphPlot],{HighlightColor->LightBlue,HighlightThickness->.15}];
    

    Some of the code above could be made a little more robust, but it works:

    GraphPlotHighlight[{b->c,a->b,c->a,e->c},{b,c,e},VertexLabeling->True,HighlightColor->LightRed,HighlightThickness->.1,VertexRenderingFunction -> ({White, EdgeForm[Black], Disk[#, .06], 
    Black, Text[#2, #1]} &)]
    

    Mathematica graphics


    EDIT #1: A cleaned up version of this code can be found at http://gist.github.com/663438

    EDIT #2: As discussed in the comments below, the pattern that my edges must match is a list of edge rules with optional labels. This is slightly less general than what is used by the GraphPlot function (and by the version in the above gist) where the edge rules are also allowed to be wrapped in a Tooltip.

    To find the exact pattern used by GraphPlot I repeatedly used Unprotect[fn];ClearAttributes[fn,ReadProtected];Information[fn] where fn is the object of interest until I found that it used the following (cleaned up) function:

    Network`GraphPlot`RuleListGraphQ[x_] := 
      ListQ[x] && Length[x] > 0 && 
        And@@Map[Head[#1] === Rule 
             || (ListQ[#1] && Length[#1] == 2 && Head[#1[[1]]] === Rule) 
             || (Head[#1] === Tooltip && Length[#1] == 2 && Head[#1[[1]]] === Rule)&, 
          x, {1}]
    

    I think that my edges:{((_ -> _) | (List|Tooltip)[_ -> _, _])..} pattern is equivalent and more concise...

提交回复
热议问题