Skip to content

plot

Signature/Parameters

def plot(self, graph_style = None, nodes_label = None, nodes_position = None, estimates = None, node_subset = None, node_shape = None, node_size = None, node_color = None, node_border_color = None, node_border_style = None, node_border_width = None, node_latent_show = True, show_labels = True, use_labels = True, node_label_color = 'black', node_label_fontsize = None, node_label_fontweight = 'normal', node_label_adj_x = 0, node_label_adj_y = 0, node_label_box = None, node_label_box_style = 'square', node_label_box_margin = 0.5, edge_subset = None, edge_color = None, edge_style = None, edge_arc = None, edge_linewidth = None, edge_head_size = None, edge_head_style = None, edge_margin_tail = None, edge_margin_head = None, edge_label = None, edge_label_color_background = 'white', edge_label_color_border = 'white', edge_label_size = None, edge_label_color = None, edge_label_alpha = None, edge_label_rotate = None, edge_label_position = None, edge_label_estimates_sig_level = 0.05, edge_label_estimates_colors = {'negative': 'red', 'positive': 'blue'}, edge_label_estimates_face = None, edge_label_estimates_show_sig = True, edge_label_estimates_show_sig_alpha = {'Yes': 1, 'No': 0.2}, edge_label_estimates_show_ci = False, edge_label_estimates_show_ci_round = 4, edge_label_pvalue = None, edge_label_font_family = None, legend_show = True, legend_title = 'Nodes', legend_title_align = 'left', legend_title_weight = 'bold', legend_title_size = 12, legend_omit_cases = ['Observed'], legend_keys = None, legend_loc = 'best', legend_fontsize = 10, legend_frame = False, legend_kws = {}, title = None, title_loc = 'left', title_kws = {}, figsize = [6, 4], usetex = True, latex_packages = None, ax = None, show_plot = None, *args, **kws)

Render the DAG using matplotlib with extensive styling controls.

Parameters:

Name Type Description Default
graph_style (dict, str, None)

If str, it must be a name of a predefined built-in style (see causalinf.gcm.styles()). When None, falls back to the global plotting option. If dict, it must match the names of the keys of the built-in styles (see causalinf.gcm.styles(which=’default’)).

None
nodes_label dict[str, str] or None

Mapping from node names to display labels.

None
nodes_position dict[str, tuple[float, float]] or None

Coordinates to override automatic layout positions.

None
estimates estimate or None

Output of causalinf.scm.estimate used to annotate edges with estimates and p-values.

None
node_subset dict[str, list[str]] or None

Restrict plotting to specific node groups (e.g., observed, latent). Defaults to all nodes.

None
node_latent_show bool

If False, omit latent nodes while preserving their effects via arcs. Defaults to True.

True
show_labels bool

Display node labels when True (default).

True
use_labels bool

When True (default), prefer custom labels over node names.

True
node_ dict or scalar or None

Control the visual attributes of nodes. Can be applied per node, per group based on node role, or to all nodes. Which case happends depends on the input:

  • str, float, int -> apply to all nodes
  • None -> use defaults based on GCM styles by type (see causalinf.gcm.styles())
  • dict -> apply to nodes or types based on the keys, which can be:

    • Node Role: ‘Exposure’, “Outcome”, “Latent”, “Observed”, or any user-defined node role
    • Node name

Accepted values for each parameter:

  • _shape: str
  • _size: int, float
  • _color: str

  • _border_color: str

  • _border_style: str (‘-‘, ‘solid’, ‘–‘, ‘dashed’, “:”, ‘dotted’)
  • _border_width: int, float

  • _label_color: str

  • _label_fontsize: int, float
  • _label_fontweight: str (normal, bold, italic)
  • _label_adj_x: int, float
  • _label_adj_y: int, float
  • _label_box_style: str (“round”’)
  • _label_box_margin: int, float
required
node_latent_show

If True, show latent nodes

True
node_label_box

If True, draw box around the label when using ‘rectangle’ node style.

None
edge_

Control the visual attributes of edges. Can be applied per edge, per edge type, or to all edges. Which case happends depends on the input:

  • scalar -> apply to all edges
  • None -> use defaults by edge type
  • dict -> keys can be:
    • edge type (case-insensitive):
      • ‘directed’ -> apply to all directed edges
      • ‘bidirected’ -> apply to all bidirected edges
      • ‘undirected’ -> apply to all undirected edges
    • actual edges. Example:
      • (‘D’, ‘Y’) apply to the “D -> Y” directed edge
      • ((‘D’, ‘Y’), (‘Y’, ‘D’)) apply to the “D <-> Y” bidirected edge
      • frozenset({‘D’, ‘Y’}) apply to the “D – Y” undirected edge

Accepted values for each parameter:

  • _color: str
  • _style: str (‘-‘, ‘solid’, ‘–‘, ‘dashed’, “:”, ‘dotted’)
  • _arc: float
  • _linewidth: float
  • _head_size: float
  • _head_style: str (‘->’, ‘-|>’)
  • _margin_tail: float
  • _margin_head: float

  • _label: str

  • _label_color_background: str
  • _label_color_border: str
  • _label_size: float
  • _label_color: str
  • _label_alpha: float
  • _label_rotate: bool
  • _label_position: float
required
edge_subset dict[str, list] or None

Limit plotting to selected edges by type.

None
edge_label_estimates_sig_level float

Significance level used when estimates include confidence bounds.

0.05
edge_label_estimates_colors dict or None

Colors for negative and positive estimate labels. Use None to keep the default edge label color. Defaults to {"negative": "red", "positive": "blue"}.

{'negative': 'red', 'positive': 'blue'}
edge_label_estimates_face dict or None

Font weight for negative and positive estimate labels, e.g. {"negative": "normal", "positive": "bold"}. Use None to keep the normal label weight.

None
edge_label_estimates_show_sig bool

Append significance stars from the estimates summary when True. Defaults to True.

True
edge_label_estimates_show_sig_alpha dict or None

Alpha values keyed by "Yes" and "No", where "Yes" means the estimate p-value is at or below edge_label_estimates_sig_level. Use None to keep the default edge label alpha. Defaults to {"Yes": .5, "No": 1}.

{'Yes': 1, 'No': 0.2}
edge_label_estimates_show_ci bool

Add confidence intervals below the estimate label when True. Defaults to False.

False
edge_label_estimates_show_ci_round int

Number of decimal places used for confidence interval bounds. Defaults to 4.

4
edge_label_pvalue dict or None

P-value annotations keyed by edge.

None
edge_label_font_family str or None

Font family for edge labels.

None
legend_show bool

Display the legend when True (default).

True
legend_title str

Legend title. Defaults to 'Nodes'.

'Nodes'
legend_title_align (left, center, right)

Horizontal alignment for the legend title.

'left'
legend_title_weight str

Font weight for the legend title.

'bold'
legend_title_size int

Legend title font size.

12
legend_omit_cases list[str]

Node role labels to omit from the legend.

['Observed']
legend_keys dict or None

Custom legend entries keyed by role.

None
legend_loc str

Legend placement for matplotlib.axes.Axes.legend.

'best'
legend_fontsize int

Legend text size.

10
legend_frame bool

Draw a frame around the legend when True.

False
legend_kws dict

Additional keyword arguments forwarded to legend.

{}
title str or None

Plot title.

None
title_loc (left, center, right)

Title alignment. Defaults to 'left'.

'left'
title_kws dict

Additional title styling options.

{}
figsize Sequence[float]

Width and height (in inches) for the created figure. Defaults to [6, 4].

[6, 4]
usetex bool

Enable LaTeX rendering for text. Defaults to True.

True
ax Axes or None

Existing axis to draw on. A new figure and axis are created when None.

None
show_plot bool or None

Override global option controlling whether plt.show() is called.

None
*args

Additional positional arguments forwarded to the internal plotting helpers.

()
**kws

Extra keyword arguments forwarded to the internal plotting helpers.

{}

Returns:

Type Description
Axes

plot object and axis on which the graph is drawn.

Examples:

>>> G = DAG(graph="X -> Y")
>>> plt, ax = G.plot(figsize=(4, 3), show_plot=False)
True
>>> dag  = '''
>>> D -> M1
>>> M1 -- M2
>>> M2 -> Y
>>> M3 -> Y
>>> D <-> Y
>>> D  -> Y
>>> Z -> {D, Y}
>>> '''
>>> pos = {'D': (0,0),
>>>        'Y': (1,0),
>>>        'Z': (.5, -1),
>>>        'M1': (.25, 1),
>>>        'M2': (.75, 1),
>>>        'M3': (1.75, 1),
>>>        }
>>> pos2 = {'D': (.5,0),
>>>        'Y': (1,0),
>>>        'Z': (.5, -1),
>>>        'M1': (.25, 1),
>>>        'M2': (.75, 1),
>>>        'M3': (1.75, 1),
>>>        }
>>> roles = {'Exposure': "D",
>>>          'Outcome' : "Y",
>>>          "Latent"  : 'Z',
>>>          "M2 role" : "M2"
>>>          }
>>> labels = {"D": "$\widetilde{D}$",
>>>           "M1":'$M_1$',
>>>           'Y': "Outcome"}
>>> labels2 = {"D": "$\widetilde{D}_i$"}
>>> edge_label = {('D', 'M1') : 1,
>>>               ('M2', 'Y') : -1,
>>>               ('M3', 'Y') : 'a',
>>>               ('D', 'Y') : 'bsd;fkajsd;',
>>>               ('Z', 'D') : '$\beta$',
>>>               ('Z', 'Y'): 'asccc',
>>>               (('D', 'Y'), ('Y', 'D')): 'abc',
>>>                # ('M2', 'M1') : 1234, # no label for undireted edges
>>>               }
>>> 
>>> G = gcm.DAG(dag,  nodes_role=roles, nodes_position=pos, nodes_label=labels)  # 
>>> G.plot()
>>> 
>>> G.plot(node_color='red')
>>> G.plot(node_color={'D':'red'})
>>> G.plot(node_border_color={'D':'red'})
>>> G.plot(node_border_color={'Z':'red'})
>>> G.plot(node_border_color={'Z':'red'}, node_border_style={'D':':'})
>>> G.plot(node_border_color={'Z':'red'}, node_border_style={'D':':', 'Z':'solid'})
Source code in causalinf/gcm.py
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
def plot(self,
         # nodes
         graph_style = None,
         nodes_label=None,
         nodes_position=None,
         estimates=None,
         # node
         node_subset=None,
         node_shape=None,
         node_size = None,
         node_color = None,
         node_border_color=None,
         node_border_style=None,
         node_border_width=None,
         node_latent_show=True,
         # node label
         show_labels = True,
         use_labels = True,
         node_label_color='black',
         node_label_fontsize=None,
         node_label_fontweight='normal',
         node_label_adj_x=0,
         node_label_adj_y=0,
         node_label_box=None,
         node_label_box_style="square",
         node_label_box_margin=.5,
         # edges
         edge_subset=None,
         edge_color=None,
         edge_style=None,
         edge_arc = None,
         edge_linewidth = None,
         edge_head_size = None,
         edge_head_style = None,
         edge_margin_tail=None,
         edge_margin_head=None,
         # edges labels
         edge_label=None,
         edge_label_color_background='white',
         edge_label_color_border='white',
         edge_label_size=None,
         edge_label_color=None,
         edge_label_alpha=None,
         edge_label_rotate=None,
         edge_label_position=None,
         edge_label_estimates_sig_level=0.05,
         edge_label_estimates_colors={"negative":"red", "positive":"blue"},
         edge_label_estimates_face=None,
         edge_label_estimates_show_sig=True,
         edge_label_estimates_show_sig_alpha={"Yes": 1, "No": .2},
         edge_label_estimates_show_ci=False,
         edge_label_estimates_show_ci_round=4,
         edge_label_pvalue=None,
         edge_label_font_family = None,
         # legend
         legend_show=True,
         legend_title='Nodes',
         legend_title_align='left',
         legend_title_weight='bold',
         legend_title_size=12,
         legend_omit_cases=['Observed'],
         legend_keys=None,
         legend_loc='best',
         legend_fontsize=10,
         legend_frame=False,
         legend_kws={},
         #
         title = None,
         title_loc = 'left',
         title_kws = {},
         # 
         figsize = [6, 4],
         usetex = True,
         latex_packages = None,
         ax=None,
         show_plot=None,
         *args,
         **kws
         ):
    """
    Render the DAG using matplotlib with extensive styling controls.

    Parameters
    ----------
    graph_style : dict, str, None, optional
        If str, it must be a name of a predefined built-in style
        (see causalinf.gcm.styles()). When ``None``, falls
        back to the global plotting option. If dict, it must
        match the names of the keys of the built-in styles
        (see causalinf.gcm.styles(which='default')).
    nodes_label : dict[str, str] or None, optional
        Mapping from node names to display labels.
    nodes_position : dict[str, tuple[float, float]] or None, optional
        Coordinates to override automatic layout positions.
    estimates : estimate or None, optional
        Output of ``causalinf.scm.estimate`` used to annotate edges with
        estimates and p-values.
    node_subset : dict[str, list[str]] or None, optional
        Restrict plotting to specific node groups (e.g., observed,
        latent). Defaults to all nodes.
    node_latent_show : bool, optional
        If ``False``, omit latent nodes while preserving their effects via
        arcs. Defaults to ``True``.
    show_labels : bool, optional
        Display node labels when ``True`` (default).
    use_labels : bool, optional
        When ``True`` (default), prefer custom labels over node names.

    node_ : dict or scalar or None, optional
        Control the visual attributes of nodes. Can be applied per node,
        per group based on node role, or to all nodes.
        Which case happends depends on the input:

        * str, float, int -> apply to all nodes
        * None   -> use defaults based on GCM styles by type (see causalinf.gcm.styles())
        * dict   -> apply to nodes or types based on the keys, which can be:

            - Node Role: 'Exposure', "Outcome", "Latent", "Observed", or any user-defined node role
            - Node name

        Accepted values for each parameter:

        *  _shape: ``str``
        *  _size: int, ``float``
        *  _color: ``str``

        *  _border_color: ``str``
        *  _border_style: ``str`` ('-', 'solid', '--', 'dashed', ":", 'dotted')
        *  _border_width: ``int, float``

        *  _label_color: ``str``
        *  _label_fontsize: ``int, float``
        *  _label_fontweight: ``str`` (normal, bold, italic)
        *  _label_adj_x: int, ``float``
        *  _label_adj_y: int, ``float``
        *  _label_box_style: ``str`` ("round"')
        *  _label_box_margin: ``int, float``

    node_latent_show: bool
        If True, show latent nodes

    node_label_box: bool, optional
        If True, draw box around the label when using 'rectangle' node style.

    edge_  : dict or scalar or None, optional
        Control the visual attributes of edges. Can be applied per edge,
        per edge type, or to all edges. Which case happends depends on the input:

        - scalar -> apply to all edges
        - None   -> use defaults by edge type
        - dict   -> keys can be:
            * edge type (case-insensitive):
                * 'directed' -> apply to all directed edges
                * 'bidirected' -> apply to all bidirected edges
                * 'undirected'  -> apply to all undirected edges
            * actual edges. Example:
                - ('D', 'Y') apply to the "D -> Y" directed edge
                - (('D', 'Y'), ('Y', 'D')) apply to the "D <-> Y" bidirected edge
                - frozenset({'D', 'Y'}) apply to the "D -- Y" undirected edge

        Accepted values for each parameter:

        * _color: ``str``
        * _style: ``str`` ('-', 'solid', '--', 'dashed', ":", 'dotted')
        * _arc: ``float``
        * _linewidth: ``float``
        * _head_size: ``float``
        * _head_style: ``str`` ('->', '-|>')
        * _margin_tail: ``float``
        * _margin_head: ``float``

        * _label: ``str``
        * _label_color_background: ``str``
        * _label_color_border: ``str``
        * _label_size: ``float``
        * _label_color: ``str``
        * _label_alpha: ``float``
        * _label_rotate: bool
        * _label_position:  ``float``

    edge_subset : dict[str, list] or None, optional
        Limit plotting to selected edges by type.

    edge_label_estimates_sig_level : float, optional
        Significance level used when estimates include confidence bounds.
    edge_label_estimates_colors : dict or None, optional
        Colors for negative and positive estimate labels. Use ``None`` to
        keep the default edge label color. Defaults to
        ``{"negative": "red", "positive": "blue"}``.
    edge_label_estimates_face : dict or None, optional
        Font weight for negative and positive estimate labels, e.g.
        ``{"negative": "normal", "positive": "bold"}``. Use ``None`` to
        keep the normal label weight.
    edge_label_estimates_show_sig : bool, optional
        Append significance stars from the estimates summary when ``True``.
        Defaults to ``True``.
    edge_label_estimates_show_sig_alpha : dict or None, optional
        Alpha values keyed by ``"Yes"`` and ``"No"``, where ``"Yes"``
        means the estimate p-value is at or below
        ``edge_label_estimates_sig_level``. Use ``None`` to keep the
        default edge label alpha. Defaults to ``{"Yes": .5, "No": 1}``.
    edge_label_estimates_show_ci : bool, optional
        Add confidence intervals below the estimate label when ``True``.
        Defaults to ``False``.
    edge_label_estimates_show_ci_round : int, optional
        Number of decimal places used for confidence interval bounds.
        Defaults to ``4``.

    edge_label_pvalue : dict or None, optional
        P-value annotations keyed by edge.

    edge_label_font_family : str or None, optional
        Font family for edge labels.

    legend_show : bool, optional
        Display the legend when ``True`` (default).
    legend_title : str, optional
        Legend title. Defaults to ``'Nodes'``.
    legend_title_align : {'left', 'center', 'right'}, optional
        Horizontal alignment for the legend title.
    legend_title_weight : str, optional
        Font weight for the legend title.
    legend_title_size : int, optional
        Legend title font size.
    legend_omit_cases : list[str], optional
        Node role labels to omit from the legend.
    legend_keys : dict or None, optional
        Custom legend entries keyed by role.
    legend_loc : str, optional
        Legend placement for ``matplotlib.axes.Axes.legend``.
    legend_fontsize : int, optional
        Legend text size.
    legend_frame : bool, optional
        Draw a frame around the legend when ``True``.
    legend_kws : dict, optional
        Additional keyword arguments forwarded to ``legend``.
    title : str or None, optional
        Plot title.
    title_loc : {'left', 'center', 'right'}, optional
        Title alignment. Defaults to ``'left'``.
    title_kws : dict, optional
        Additional title styling options.
    figsize : Sequence[float], optional
        Width and height (in inches) for the created figure. Defaults to
        ``[6, 4]``.
    usetex : bool, optional
        Enable LaTeX rendering for text. Defaults to ``True``.
    ax : matplotlib.axes.Axes or None, optional
        Existing axis to draw on. A new figure and axis are created when
        ``None``.
    show_plot : bool or None, optional
        Override global option controlling whether ``plt.show()`` is called.
    *args :
        Additional positional arguments forwarded to the internal plotting
        helpers.
    **kws :
        Extra keyword arguments forwarded to the internal plotting helpers.

    Returns
    -------
    matplotlib.axes.Axes
        plot object and axis on which the graph is drawn.

    Examples
    --------
    >>> G = DAG(graph="X -> Y")
    >>> plt, ax = G.plot(figsize=(4, 3), show_plot=False)
    True

    >>> dag  = '''
    >>> D -> M1
    >>> M1 -- M2
    >>> M2 -> Y
    >>> M3 -> Y
    >>> D <-> Y
    >>> D  -> Y
    >>> Z -> {D, Y}
    >>> '''
    >>> pos = {'D': (0,0),
    >>>        'Y': (1,0),
    >>>        'Z': (.5, -1),
    >>>        'M1': (.25, 1),
    >>>        'M2': (.75, 1),
    >>>        'M3': (1.75, 1),
    >>>        }
    >>> pos2 = {'D': (.5,0),
    >>>        'Y': (1,0),
    >>>        'Z': (.5, -1),
    >>>        'M1': (.25, 1),
    >>>        'M2': (.75, 1),
    >>>        'M3': (1.75, 1),
    >>>        }
    >>> roles = {'Exposure': "D",
    >>>          'Outcome' : "Y",
    >>>          "Latent"  : 'Z',
    >>>          "M2 role" : "M2"
    >>>          }
    >>> labels = {"D": "$\widetilde{D}$",
    >>>           "M1":'$M_1$',
    >>>           'Y': "Outcome"}
    >>> labels2 = {"D": "$\widetilde{D}_i$"}
    >>> edge_label = {('D', 'M1') : 1,
    >>>               ('M2', 'Y') : -1,
    >>>               ('M3', 'Y') : 'a',
    >>>               ('D', 'Y') : 'bsd;fkajsd;',
    >>>               ('Z', 'D') : '$\\beta$',
    >>>               ('Z', 'Y'): 'asccc',
    >>>               (('D', 'Y'), ('Y', 'D')): 'abc',
    >>>                # ('M2', 'M1') : 1234, # no label for undireted edges
    >>>               }
    >>> 
    >>> G = gcm.DAG(dag,  nodes_role=roles, nodes_position=pos, nodes_label=labels)  # 
    >>> G.plot()
    >>> 
    >>> G.plot(node_color='red')
    >>> G.plot(node_color={'D':'red'})
    >>> G.plot(node_border_color={'D':'red'})
    >>> G.plot(node_border_color={'Z':'red'})
    >>> G.plot(node_border_color={'Z':'red'}, node_border_style={'D':':'})
    >>> G.plot(node_border_color={'Z':'red'}, node_border_style={'D':':', 'Z':'solid'})
    """
    from . import scm as causalinf_scm

    assert estimates is None or isinstance(estimates, causalinf_scm.estimate), (
        "'estimates' must be either None or an object of causalinf.scm.estimate ")
    assert isinstance(latex_packages, list) or latex_packages is None, "latex_packages must be None or a list"

    default_usetex = plt.rcParams["text.usetex"] 
    plt.rcParams["text.usetex"] = usetex
    latex_packages_base = ["amsmath", "amssymb", "siunitx", "bm", "wasysym", "marvosym"]
    packages = latex_packages_base + (latex_packages or [])
    plt.rcParams['text.latex.preamble'] = rf"\usepackage{{{', '.join(packages)}}}"

    show_plot = show_plot if not None else get_options('show_plot')

    # collect arguments
    pars = dict(locals())      # {'node_position':..., 'arg2':..., 'args':(...), 'kws':{...}}
    args = pars.pop('args') # extra positional
    kws  = pars.pop('kws')  # extra keyword

    estimate_label_sign = {}
    estimate_label_pvalue = {}

    # use estimates as labels
    if estimates is not None:
        edge_label, edge_label_pvalue, estimate_label_sign = (
            self.__plot_collect_labels_estimate__(
                estimates,
                show_sig=edge_label_estimates_show_sig,
                show_ci=edge_label_estimates_show_ci,
                show_ci_round=edge_label_estimates_show_ci_round
            )
        )
        estimate_label_pvalue = edge_label_pvalue

    # figure 
    # ------
    G_draw = self.__plot_create_nx__()
    if ax is None:
        fig, ax = plt.subplots(figsize=figsize, tight_layout=True)
    plt.sca(ax)

    # styles
    # ------
    graph_style = graph_style or get_options('graph_style')
    style_dict = resolve_graph_style(graph_style, GRAPH_STYLES)

    # nodes 
    # -----
    node_subset       = self.__plot_nodes_subset__(node_subset, node_latent_show)
    nodes_position    = self.__plot_nodes_positions__(G_draw, nodes_position)
    node_size         = self._plot_parse_aes_node('node_size', node_size, style_dict)
    node_color        = self._plot_parse_aes_node('node_color', node_color, style_dict)
    node_shape        = self._plot_parse_aes_node('node_shape', node_shape, style_dict)
    node_border_width = self._plot_parse_aes_node('node_border_width', node_border_width, style_dict)
    node_border_color = self._plot_parse_aes_node('node_border_color', node_border_color, style_dict)
    node_border_style = self._plot_parse_aes_node("node_border_style", node_border_style, style_dict)

    for _, nodes in node_subset.items():
        for node in nodes:
            fig_nodes = nx.draw_networkx_nodes(
                G_draw,
                nodes_position,
                nodelist=[node],
                ax=ax,
                # 
                node_size  = node_size[node],
                node_color = node_color[node],
                node_shape = node_shape[node],
                linewidths = node_border_width[node],
                edgecolors = node_border_color[node],
                alpha      = None,
                cmap       = None,
                vmin       = None,
                vmax       = None,
                label      = None,
                margins    = None, 
                hide_ticks = True
            )
            fig_nodes.set_linestyle(node_border_style[node])

    # nodes labels 
    # ------------
    if show_labels:
        nodes = set(itertools.chain.from_iterable(node_subset.values()))
        nodes_label = self.nodes_label | (nodes_label or {})
        adj_x = self.__plot_label_adj__(node_label_adj_x, nodes_label)
        adj_y = self.__plot_label_adj__(node_label_adj_y, nodes_label)

        fc        = self._plot_parse_aes_node('node_color', node_color, style_dict)
        fontweight= self._plot_parse_aes_node('node_label_fontweight', node_label_fontweight, style_dict)
        fontsize  = self._plot_parse_aes_node('node_label_fontsize', node_label_fontsize, style_dict)
        boxstyle  = self._plot_parse_aes_node('node_label_box_style', node_label_box_style, style_dict)
        boxmargin = self._plot_parse_aes_node('node_label_box_margin', node_label_box_margin, style_dict)

        ec        = self._plot_parse_aes_node('node_border_color', node_border_color, style_dict)
        lw        = self._plot_parse_aes_node('node_border_width', node_border_width, style_dict)
        linestyle = self._plot_parse_aes_node('node_border_style', node_border_style, style_dict)
        node_label_box = self._plot_parse_aes_node('node_label_box', node_label_box, style_dict)

        for node in nodes:
            label = nodes_label.get(node, node) if use_labels else node
            role  = self.nodes_info[node]['role']
            x, y  = nodes_position[node] if nodes_position and all(nodes_position[node]) else \
                self.nodes_info[node]['position'] 

            if node_label_box[node]:
                bbox = {"boxstyle": f"{boxstyle[node]},pad={boxmargin[node]}",
                        "fc": fc[node],
                        "ec": ec[node],
                        "lw": lw[node],
                        "linestyle": linestyle[node],
                        "alpha": 1
                        }
            else:
                bbox = None

            if fontweight[node]=='bold':
                label = f"\\textbf{{{label}}}"
            elif fontweight[node]=='italic':
                label = f"\\textit{{{label}}}"

            plt.text(x + adj_x[node],
                     y + adj_y[node],
                     label,
                     fontweight = 'normal',
                     fontsize   = fontsize[node],
                     ha = 'center',
                     va = 'center',
                     bbox = bbox)

    # edges and edges labels
    # ----------------------
    nodes = set(itertools.chain.from_iterable(node_subset.values()))

    style            = self._plot_parse_aes_edge("edge_style", edge_style, style_dict)
    color            = self._plot_parse_aes_edge("edge_color", edge_color, style_dict)
    arc              = self._plot_parse_aes_edge("edge_arc", edge_arc, style_dict)
    width            = self._plot_parse_aes_edge("edge_linewidth", edge_linewidth, style_dict)
    arrow_head_size  = self._plot_parse_aes_edge("edge_head_size", edge_head_size, style_dict)
    arrow_head_style = self._plot_parse_aes_edge("edge_head_style", edge_head_style, style_dict)
    edge_margin_head = self._plot_parse_aes_edge("edge_margin_head", edge_margin_head, style_dict)
    edge_margin_tail = self._plot_parse_aes_edge("edge_margin_tail", edge_margin_tail, style_dict)


    edge_label_alpha    = self._plot_parse_aes_edge("edge_label_alpha", edge_label_alpha, style_dict)
    edge_label_size     = self._plot_parse_aes_edge("edge_label_size", edge_label_size, style_dict)
    edge_label_color    = self._plot_parse_aes_edge("edge_label_color", edge_label_color, style_dict)
    edge_label_rotate   = self._plot_parse_aes_edge("edge_label_rotate", edge_label_rotate, style_dict)
    edge_label_position = self._plot_parse_aes_edge("edge_label_position", edge_label_position, style_dict)
    edge_label_color_border     = self._plot_parse_aes_edge("edge_label_color_border", edge_label_color_border, style_dict)
    edge_label_color_background = self._plot_parse_aes_edge("edge_label_color_background", edge_label_color_background, style_dict)
    edge_label_font_weight = {edge: 'normal' for edge in edge_label_color}

    if estimates is not None:
        edge_label_color = self.__plot_apply_estimate_sign_feature__(
            edge_label_color,
            estimate_label_sign,
            edge_label_estimates_colors
        )
        edge_label_font_weight = self.__plot_apply_estimate_sign_feature__(
            edge_label_font_weight,
            estimate_label_sign,
            edge_label_estimates_face
        )
        edge_label_alpha = self.__plot_apply_estimate_sig_alpha__(
            edge_label_alpha,
            estimate_label_pvalue,
            edge_label_estimates_show_sig_alpha,
            edge_label_estimates_sig_level
        )

    for edge_type in ['directed', 'bidirected', 'undirected']:
        for edge in self.__getattribute__(edge_type):

            if edge_type == 'directed':
                u, v = tuple(edge)
            elif edge_type=='bidirected':
                u, v = edge[0]
            elif edge_type=='undirected':
                u, v = tuple(edge)
                edge = frozenset(edge)

            if edge_subset:
                e = set(edge) if edge_type=='undirected' else edge
                show_edge = self.edge_exist(e, edge_subset.get(edge_type, []))
            else:
                show_edge = True

            if u in nodes and v in nodes and show_edge:
                # edge
                nx.draw_networkx_edges(
                    G_draw,
                    nodes_position,
                    edgelist            = [(u, v)],
                    nodelist            = [u, v],
                    node_size           = [node_size[u], node_size[v]],
                    style               = style[edge],
                    edge_color          = color[edge],
                    connectionstyle     = f"arc3,rad={arc[edge]}",
                    arrows              = True,
                    arrowstyle          = arrow_head_style[edge],
                    arrowsize           = arrow_head_size[edge],
                    min_source_margin   = edge_margin_tail[edge],
                    min_target_margin   = edge_margin_head[edge],
                    width               = width[edge],
                    ax=ax)

                # edge label
                edge_label = edge_label or self.edge_label
                label = edge_label.get(edge, '')
                rotate = edge_label_rotate if edge_label_rotate is not None else True # must keep "is not None" here
                nx.draw_networkx_edge_labels(
                    G_draw,
                    pos         = nodes_position,
                    edge_labels = {(u, v): label},
                    bbox        = dict(facecolor=edge_label_color_background[edge],
                                       edgecolor=edge_label_color_border[edge]),
                    alpha       = edge_label_alpha[edge],
                    font_size   = edge_label_size[edge], 
                    font_color  = edge_label_color[edge], 
                    font_weight = edge_label_font_weight[edge],
                    rotate      = edge_label_rotate[edge], 
                    label_pos   = edge_label_position[edge], 
                    font_family = edge_label_font_family,
                    connectionstyle = f"arc3,rad={arc[edge]}",
                    ax          = ax
                )

    # legend (aggreagate per role, not per node)
    # ------
    if legend_show:
        keys = []
        for role, nodes in node_subset.items():
            if role not in legend_omit_cases:
                # collect aes for all latent nodes
                marker          = []
                color           = []
                markeredgecolor = []
                markerfacecolor = []
                linestyle       = []
                for i, node in enumerate(nodes):
                    linestyle       += [node_border_style[node]]
                    marker          += [''] if linestyle[i] in ['--', 'dotted', 'dashed', ':'] else ['o']
                    color           += [node_border_color[node]]#['black'] if role == 'Latent' else ['white']
                    markeredgecolor += [node_border_color[node]]
                    markerfacecolor += [node_color[node]]

                # add only unique aes to legend
                for marker, color, markeredgecolor, markerfacecolor, linestyle in \
                        set(zip(marker, color, markeredgecolor, markerfacecolor, linestyle)):
                    keys += [
                        Line2D(
                            [0], [0],
                            marker=marker,
                            color = color,
                            label = role,
                            markersize = 10,
                            markeredgecolor=markeredgecolor,
                            markerfacecolor=markerfacecolor,
                            linestyle=linestyle
                        )]
        if keys: 
            legend = plt.legend(handles        = keys,
                                title          = legend_title,
                                title_fontsize = legend_title_size,
                                alignment      = legend_title_align,
                                # title_weight   = legend_title_weight,
                                loc            = legend_loc,
                                fontsize       = legend_fontsize,
                                frameon        = legend_frame,
                                **legend_kws
                                )
            if legend_title_weight=='bold' and legend_title:
                legend.set_title(title=f'\\textbf{{{legend_title}}}', prop={'weight': 'bold'})

    # title 
    # -----
    if title:
        plt.title(label=title, loc=title_loc, **title_kws)

    plt.axis("off")
    plt.tight_layout()
    if show_plot:
        plt.show()
    plt.rcParams["text.usetex"] = default_usetex

    return plt, ax