Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

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

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

# -*- coding: utf-8 -*- 

# 

# Copyright (c) 2017-2018 Spotify AB 

# 

# Licensed under the Apache License, Version 2.0 (the "License"); 

# you may not use this file except in compliance with the License. 

# You may obtain a copy of the License at 

# 

# http://www.apache.org/licenses/LICENSE-2.0 

# 

# Unless required by applicable law or agreed to in writing, software 

# distributed under the License is distributed on an "AS IS" BASIS, 

# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

# See the License for the specific language governing permissions and 

# limitations under the License. 

""" 

Module for chart plots. 

 

""" 

 

import bokeh 

import pandas as pd 

import numpy as np 

from chartify._core.colors import Color, color_palettes 

from chartify._core.axes import NumericalYMixin, NumericalXMixin 

 

from scipy.stats.kde import gaussian_kde 

 

 

class BasePlot: 

"""Base for all plot classes.""" 

 

def __init__(self, chart, y_range_name="default"): 

self._chart = chart 

self._y_range_name = y_range_name 

 

@staticmethod 

def _axis_format_precision(max_value, min_value): 

difference = abs(max_value - min_value) 

precision = abs(int(np.floor( 

np.log10(difference if difference else 1)))) + 1 

zeros = ''.join(['0']*precision) 

return "0,0.[{}]".format(zeros) 

 

@classmethod 

def _get_plot_class(cls, x_axis_type, y_axis_type): 

if x_axis_type == 'categorical' and y_axis_type == 'categorical': 

return PlotCategoricalXY 

elif x_axis_type not in ('categorical', 

'density') and y_axis_type not in ( 

'categorical', 'density'): 

return PlotNumericXY 

elif x_axis_type == 'density' and y_axis_type == 'density': 

return PlotDensityXY 

elif x_axis_type == 'datetime' and y_axis_type == 'density': 

raise NotImplementedError( 

"Plot for this axis type combination not yet implemented.") 

elif x_axis_type == 'density' or y_axis_type == 'density': 

return PlotNumericDensityXY 

else: 

return PlotMixedTypeXY 

 

def _get_color_and_order(self, 

data_frame, 

color_column, 

color_order, 

categorical_columns=None): 

""" 

Returns: 

colors: List of hex colors or factor_cmap. 

color_order: List of values for each color. 

""" 

if color_column is None: 

colors = [self._chart.style.color_palette.next_color()] 

color_order = [None] 

else: 

# Determine color order or verify integrity of specified order. 

if color_order is None: 

color_order = sorted(data_frame[color_column].unique()) 

else: 

# Check that all color factors are present in the color order. 

if not set(data_frame[color_column].unique()).issubset( 

set(color_order)): 

raise ValueError("""Color order must include 

all unique factors of variable `%s`.""" % 

color_column) 

 

next_colors = self._chart.style.color_palette.next_colors( 

color_order) 

if categorical_columns is None: # Numeric data 

colors = next_colors 

else: 

# # Color column must be in the categorical_columns 

# try: 

# color_index = categorical_columns.index(color_column) 

# color_label = 'factors' 

# except ValueError: 

# color_label = 'color_column' 

# color_index = 0 

# raise ValueError( 

# '''`color_column` must be present 

# in the `categorical_columns`''' 

# ) 

color_label = 'color_column' 

color_index = 0 

color_order = [str(factor) for factor in color_order] 

colors = bokeh.transform.factor_cmap( 

color_label, 

palette=next_colors, 

factors=color_order, 

start=color_index, 

end=color_index + 1, 

) 

return colors, color_order 

 

@staticmethod 

def _plot_with_legend(method, **kwargs): 

"""Call plotting method with the associated kwargs. 

 

Removes the legend parameter if it is set to None because 

Bokeh breaks if None is passed to a legend parameter 

 

""" 

legend_label = kwargs.pop('legend_label', None) 

legend_group = kwargs.pop('legend_group', None) 

 

if legend_label is not None: 

return method(**kwargs, legend_label=legend_label) 

elif legend_group is not None: 

return method(**kwargs, legend_group=legend_group) 

else: 

return method(**kwargs) 

 

@staticmethod 

def _cannonical_series_name(series_name): 

if series_name is None: 

series_name = '' 

return 'Series:{}'.format(series_name) 

 

@staticmethod 

def _named_column_data_source(data_frame, series_name): 

"""Ensure consistent naming of column data sources. 

Naming ensures that Chart.data property will populate correctly. 

""" 

cannonical_series_name = BasePlot._cannonical_series_name(series_name) 

return bokeh.models.ColumnDataSource( 

data_frame, name=cannonical_series_name) 

 

def _cast_datetime_axis(self, data_frame, column): 

if self._chart._x_axis_type == 'datetime': 

if data_frame[column].dtype != 'datetime64[ns]': 

return data_frame.astype({column: 'datetime64[ns]'}) 

return data_frame 

 

def __getattr__(self, item): 

"""Override attribute error 

""" 

raise AttributeError("""Plot `{}` not avaiable for the given Chart. 

Try changing the Chart parameters x_axis_type and y_axis_type. 

""".format(item)) 

 

def _set_numeric_axis_default_format(self, data_frame, 

x_column=None, y_column=None): 

"""Set numeric axis range based on the input data. 

""" 

 

if isinstance(self._chart.axes, NumericalXMixin): 

# Warn user if they try to plot date data on a non-datetime axis. 

if data_frame[x_column].dtype == 'datetime64[ns]': 

raise ValueError("""Set chartify.Chart(x_axis_type='datetime') 

when plotting datetime data.""") 

# Warn user if they try to plot date data that hasn't been cast 

# to the proper dtype. 

elif data_frame[x_column].dtype == 'O': 

raise ValueError("""Attempting to plot `{}` on a numeric 

axis. Ensure that chartify.Chart x_axis_type and y_axis_type 

are set properly, or cast your input data appropriately. 

""".format(x_column)) 

 

if isinstance(self._chart.axes, NumericalXMixin): 

max_x_value = data_frame[x_column].max() 

min_x_value = data_frame[x_column].min() 

max_x_value, min_x_value = max(max_x_value, 0), min(min_x_value, 0) 

self._chart.axes.set_xaxis_tick_format( 

self._axis_format_precision(max_x_value, 

min_x_value) 

) 

 

if isinstance(self._chart.axes, NumericalYMixin): 

max_y_value = data_frame[y_column].max() 

min_y_value = data_frame[y_column].min() 

max_y_value, min_y_value = max(max_y_value, 0), min(min_y_value, 0) 

self._chart.axes.set_yaxis_tick_format( 

self._axis_format_precision(max_y_value, 

min_y_value) 

) 

 

 

class PlotCategoricalXY(BasePlot): 

"""Plot functions for categorical x & y axes: 

 

Methods: 

- heatmap 

""" 

 

def heatmap(self, 

data_frame, 

x_column, 

y_column, 

color_column, 

text_column=None, 

color_palette='RdBu', 

reverse_color_order=False, 

text_color='white', 

text_format='{:,.2f}', 

color_value_min=None, 

color_value_max=None, 

color_value_range=100): 

"""Heatmap. 

 

Args: 

data_frame (pandas.DataFrame): Data source for the plot. 

x_column (str): Column name to plot on the x axis. 

y_column (str): Column name to plot on the y axis. 

color_column (str): Column name of numerical type to plot on 

the color dimension. 

text_column (str or None): Column name of the text labels. 

color_palette (str, chartify.ColorPalette): Color palette to 

apply to the heatmap. 

See chartify.color_palettes.show() for available color palettes. 

reverse_color_order (bool): Reverse order of the color palette. 

text_color (str): Color name or hex value. 

See chartify.color_palettes.show() for available color names. 

text_format: Python string formatting to apply to the text labels. 

color_value_min (float): Minimum value for the color palette. 

If None, will default to the min value of the 

color_column dimension. 

color_value_max (float): Maximum value for the color palette. 

If None, will default to the max value of the 

color_column dimension. 

color_value_range (int): The size of the range of colors in 

the color palette. 

A larger color range will result in greater variation 

among the cell colors. 

""" 

# Cast all categorical columns to strings 

# Plotting functions will break with non-str types. 

type_map = {column: str for column in [x_column, y_column]} 

self._chart.figure.x_range.factors = data_frame[x_column].astype( 

str).unique() 

self._chart.figure.y_range.factors = data_frame[y_column].astype( 

str).unique() 

 

cast_data = data_frame[[x_column, y_column, 

color_column]].astype(type_map) 

 

source = self._named_column_data_source(cast_data, series_name=None) 

if text_color: 

text_color = Color(text_color).get_hex_l() 

if isinstance(color_palette, str): 

color_palette = color_palettes[color_palette] 

if reverse_color_order: 

color_palette = color_palette[::-1] 

color_palette = color_palette.expand_palette(color_value_range) 

color_palette = [c.get_hex_l() for c in color_palette.colors] 

 

# If not specified set the min and max value based on the data. 

if not color_value_min: 

color_value_min = data_frame[color_column].min() 

if not color_value_max: 

color_value_max = data_frame[color_column].max() 

mapper = bokeh.models.LinearColorMapper( 

palette=color_palette, low=color_value_min, high=color_value_max) 

self._chart.figure.rect( 

source=source, 

x=x_column, 

y=y_column, 

fill_color={ 

'field': color_column, 

'transform': mapper 

}, 

width=1, 

height=1, 

dilate=True, 

line_alpha=0) 

 

if text_column: 

text_font = self._chart.style._get_settings( 

'text_callout_and_plot')['font'] 

formatted_text = data_frame[text_column].map(text_format.format) 

source.add(formatted_text, 'formatted_text') 

self._chart.figure.text( 

text='formatted_text', 

x=x_column, 

y=y_column, 

source=source, 

text_align='center', 

text_baseline='middle', 

text_color=text_color, 

text_font=text_font) 

return self._chart 

 

 

class PlotNumericXY(BasePlot): 

"""Plot functions for numeric x & y axes: 

 

Methods: 

- line 

- scatter 

- text 

- area 

""" 

 

def line(self, 

data_frame, 

x_column, 

y_column, 

color_column=None, 

color_order=None, 

line_dash='solid', 

line_width=4, 

alpha=1.0): 

"""Line Chart. 

 

Note: 

This method will not automatically sort the x-axis. 

Try sorting the axis if the line graph looks strange. 

 

Args: 

data_frame (pandas.DataFrame): Data source for the plot. 

x_column (str): Column name to plot on the x axis. 

y_column (str): Column name to plot on the y axis. 

color_column (str, optional): Column name to group by on 

the color dimension. 

color_order (list, optional): List of values within the 

'color_column' for specific sorting of the colors. 

line_dash (str, optional): Dash style for the line. One of: 

- 'solid' 

- 'dashed' 

- 'dotted' 

- 'dotdash' 

- 'dashdot' 

line_width (int, optional): Width of the line 

alpha (float): Alpha value. 

""" 

settings = self._chart.style._get_settings('line_plot') 

line_cap = settings['line_cap'] 

line_join = settings['line_join'] 

 

colors, color_values = self._get_color_and_order( 

data_frame, color_column, color_order) 

 

self._set_numeric_axis_default_format(data_frame, x_column, y_column) 

 

for color_value, color in zip(color_values, colors): 

 

if color_column is None: # Single line 

sliced_data = data_frame 

else: 

sliced_data = data_frame[data_frame[color_column] == 

color_value] 

# Filter to only relevant columns. 

sliced_data = ( 

sliced_data[ 

[col for col in sliced_data.columns 

if col in ( 

x_column, y_column, color_column)]]) 

 

cast_data = self._cast_datetime_axis(sliced_data, x_column) 

 

source = self._named_column_data_source( 

cast_data, series_name=color_value) 

 

color_value = str( 

color_value) if color_value is not None else color_value 

 

self._plot_with_legend( 

self._chart.figure.line, 

legend_label=color_value, 

x=x_column, 

y=y_column, 

source=source, 

line_width=line_width, 

color=color, 

line_join=line_join, 

line_cap=line_cap, 

line_dash=line_dash, 

alpha=alpha, 

y_range_name=self._y_range_name 

) 

 

# Set legend defaults if there are multiple series. 

if color_column is not None: 

self._chart.style._apply_settings('legend') 

 

return self._chart 

 

def scatter(self, 

data_frame, 

x_column, 

y_column, 

size_column=None, 

color_column=None, 

color_order=None, 

alpha=1.0, 

marker='circle'): 

"""Scatter plot. 

 

Args: 

data_frame (pandas.DataFrame): Data source for the plot. 

x_column (str): Column name to plot on the x axis. 

y_column (str): Column name to plot on the y axis. 

size_column (str, optional): Column name of numerical values 

to plot on the size dimension. 

color_column (str, optional): Column name to group by on 

the color dimension. 

color_order (list, optional): List of values within the 

'color_column' for specific sorting of the colors. 

alpha (float): Alpha value. 

marker (str): marker type. Valid types: 

'asterisk', 'circle', 'circle_cross', 'circle_x', 'cross', 

'diamond', 'diamond_cross', 'hex', 'inverted_triangle', 

'square', 'square_x', 'square_cross', 'triangle', 

'x', '*', '+', 'o', 'ox', 'o+' 

""" 

if size_column is None: 

size_column = 6 

 

colors, color_values = self._get_color_and_order( 

data_frame, color_column, color_order) 

 

self._set_numeric_axis_default_format(data_frame, x_column, y_column) 

 

for color_value, color in zip(color_values, colors): 

 

if color_column is None: # Single series 

sliced_data = data_frame 

else: 

sliced_data = data_frame[data_frame[color_column] == 

color_value] 

# Filter to only relevant columns. 

sliced_data = ( 

sliced_data[ 

[col for col in sliced_data.columns 

if col in ( 

x_column, y_column, size_column, color_column)]]) 

cast_data = self._cast_datetime_axis(sliced_data, x_column) 

 

source = self._named_column_data_source( 

cast_data, series_name=color_value) 

 

color_value = str( 

color_value) if color_value is not None else color_value 

 

self._plot_with_legend( 

self._chart.figure.scatter, 

legend_label=color_value, 

x=x_column, 

y=y_column, 

size=size_column, 

source=source, 

fill_color=color, 

marker=marker, 

line_color=color, 

alpha=alpha, 

y_range_name=self._y_range_name) 

 

# Set legend defaults if there are multiple series. 

if color_column is not None: 

self._chart.style._apply_settings('legend') 

 

return self._chart 

 

def text(self, 

data_frame, 

x_column, 

y_column, 

text_column, 

color_column=None, 

color_order=None, 

font_size='1em', 

x_offset=0, 

y_offset=0, 

angle=0, 

text_color=None): 

"""Text plot. 

 

Args: 

data_frame (pandas.DataFrame): Data source for the plot. 

x_column (str): Column name to plot on the x axis. 

y_column (str): Column name to plot on the y axis. 

text_column (str): Column name to plot as text labels. 

color_column (str, optional): Column name to group by on the 

color dimension. 

color_order (list, optional): List of values within the 

'color_column' for specific sorting of the colors. 

font_size (str, optional): Size of text. 

x_offset (int, optional): # of pixels for horizontal text offset. 

Can be negative. Default: 0. 

y_offset (int, optional): # of pixels for vertical text offset. 

Can be negative. Default: 0. 

angle (int): Degrees from horizontal for text rotation. 

text_color (str): Color name or hex value. 

See chartify.color_palettes.show() for available color names. 

If omitted, will default to the next color in the 

current color palette. 

""" 

text_font = self._chart.style._get_settings('text_callout_and_plot')[ 

'font'] 

if text_color: 

text_color = Color(text_color).get_hex_l() 

colors, color_values = [text_color], [None] 

else: 

colors, color_values = self._get_color_and_order( 

data_frame, color_column, color_order) 

 

self._set_numeric_axis_default_format(data_frame, x_column, y_column) 

 

for color_value, color in zip(color_values, colors): 

 

if color_column is None: # Single series 

sliced_data = data_frame 

else: 

sliced_data = data_frame[data_frame[color_column] == 

color_value] 

# Filter to only relevant columns. 

sliced_data = ( 

sliced_data[ 

[col for col in sliced_data.columns 

if col in ( 

x_column, y_column, text_column, color_column)]]) 

cast_data = self._cast_datetime_axis(sliced_data, x_column) 

 

source = self._named_column_data_source( 

cast_data, series_name=color_value) 

 

self._chart.figure.text( 

text=text_column, 

x=x_column, 

y=y_column, 

text_font_size=font_size, 

source=source, 

text_color=color, 

y_offset=y_offset, 

x_offset=x_offset, 

angle=angle, 

angle_units='deg', 

text_font=text_font, 

y_range_name=self._y_range_name) 

return self._chart 

 

def area(self, 

data_frame, 

x_column, 

y_column, 

second_y_column=None, 

color_column=None, 

color_order=None, 

stacked=False): 

"""Area plot. 

 

Note: 

- When a single y_column is passed: Shade area between the 

y_values and zero. 

- Use `stacked` argument for stacked areas. 

- When both y_column and second_y_column are passed: 

Shade area between the two y_columns. 

 

Args: 

data_frame (pandas.DataFrame): Data source for the plot. 

x_column (str): Column name to plot on the x axis. 

y_column (str): Column name to plot on the y axis. 

second_y_column (str, optional): Column name to plot on 

the y axis. 

color_column (str, optional): Column name to group by on 

the color dimension. 

color_order (list, optional): List of values within the 

'color_column' for specific sorting of the colors. 

stacked (bool, optional): Stacked the areas. 

Only applicable with a single y_column. 

Default: False. 

""" 

# Vertical option only applies to density plots 

vertical = self._chart.axes._vertical 

 

alpha = 0.2 

colors, color_values = self._get_color_and_order( 

data_frame, color_column, color_order) 

 

self._set_numeric_axis_default_format(data_frame, x_column, y_column) 

 

if color_column is not None: 

data_frame = ( 

data_frame.set_index([x_column, color_column]).reindex( 

index=pd.MultiIndex.from_product( 

[data_frame[x_column].unique(), 

data_frame[color_column].unique()], 

names=[x_column, color_column])) 

.reset_index(drop=False) 

.fillna(0)) 

 

if second_y_column is None and color_column is not None: 

last_y = np.zeros(data_frame.groupby(color_column).size().iloc[0]) 

 

for color_value, color in zip(color_values, colors): 

if color_column is None: 

data = data_frame 

 

if second_y_column is None: 

alpha = .8 

y_data = np.hstack((data[y_column], 

np.zeros(len(data[y_column])))) 

else: 

y_data = pd.concat( 

[data[y_column], data[second_y_column][::-1]]) 

 

else: 

 

data = data_frame[data_frame[color_column] == color_value] 

 

if second_y_column is None: 

y_data = np.hstack((data[y_column].reset_index(drop=True), 

last_y[::-1])) 

 

if stacked: 

alpha = .8 

next_y = last_y + data[y_column].reset_index(drop=True) 

y_data = np.hstack((next_y, last_y[::-1])) 

last_y = next_y 

# Reverse order of vertical legends to ensure 

# that the order is consistent with the stack order. 

self._chart._reverse_vertical_legend = True 

else: 

y_data = pd.concat( 

[data[y_column], data[second_y_column][::-1]]) 

 

x_data = pd.concat([data[x_column], data[x_column][::-1]]) 

 

sliced_data = pd.DataFrame({x_column: x_data, y_column: y_data}) 

cast_data = self._cast_datetime_axis(sliced_data, x_column) 

source = self._named_column_data_source( 

cast_data, series_name=color_value) 

 

color_value = str( 

color_value) if color_value is not None else color_value 

 

if vertical: 

self._plot_with_legend( 

self._chart.figure.patch, 

legend_label=color_value, 

x=x_column, 

y=y_column, 

alpha=alpha, 

source=source, 

color=color, 

y_range_name=self._y_range_name 

) 

 

else: 

self._plot_with_legend( 

self._chart.figure.patch, 

legend_label=color_value, 

x=y_column, 

y=x_column, 

alpha=alpha, 

source=source, 

color=color, 

y_range_name=self._y_range_name 

) 

 

# Set legend defaults if there are multiple series. 

if color_column is not None: 

self._chart.style._apply_settings('legend') 

 

return self._chart 

 

 

class PlotNumericDensityXY(BasePlot): 

"""Plot functions for single density: 

 

Methods: 

- histogram 

- kde 

""" 

 

# def __dir__(self): 

# """Hide inherited plotting methods""" 

# inherited_public_methods = [ 

# attr for attr in dir(PlotNumericXY) 

# if callable(getattr(PlotNumericXY, attr)) 

# and not attr.startswith("_") 

# ] 

# return sorted((set(dir(self.__class__)) | set(self.__dict__.keys())) - 

# set(inherited_public_methods)) 

 

def histogram(self, 

data_frame, 

values_column, 

color_column=None, 

color_order=None, 

method='count', 

bins='auto'): 

"""Histogram. 

 

Args: 

data_frame (pandas.DataFrame): Data source for the plot. 

values_column (str): Column of numeric values. 

color_column (str, optional): Column name to group by on 

the color dimension. 

color_order (list, optional): List of values within the 

'color_column' for specific sorting of the colors. 

method (str, optional): 

- 'count': Result will contain the number of samples at each bin. 

- 'density': Result is the value of the probability density 

function at each bin. 

The PDF is normalized so that the integral over the range is 1. 

- 'mass': Result is the value of the probability mass 

function at each bin. 

The PMF is normalized so that the value is equivalent to 

the sample count at each bin divided by the total count. 

bins (int or sequence of scalars or str, optional): 

If bins is an int, it defines the number of equal-width 

bins in the given range. 

If bins is a sequence, it defines the bin edges, 

including the rightmost edge, allowing for non-uniform 

bin widths. See numpy.histogram documentation for more details. 

- ‘auto’: 

Maximum of the ‘sturges’ and ‘fd’ estimators. 

Provides good all around performance. 

- ‘fd’ (Freedman Diaconis Estimator) 

Robust (resilient to outliers) estimator that takes into 

account data variability and data size. 

- ‘doane’ 

An improved version of Sturges’ estimator that works 

better with non-normal datasets. 

- ‘scott’ 

Less robust estimator that that takes into account data 

variability and data size. 

- ‘rice’ 

Estimator does not take variability into account, only 

data size. Commonly overestimates number of bins required. 

- ‘sturges’ 

R’s default method, only accounts for data size. 

Only optimal for gaussian data and underestimates number 

of bins for large non-gaussian datasets. 

- ‘sqrt’ 

Square root (of data size) estimator, used by Excel and 

other programs for its speed and simplicity. 

""" 

vertical = self._chart.axes._vertical 

 

colors, color_values = self._get_color_and_order( 

data_frame, color_column, color_order) 

 

for color_value, color in zip(color_values, colors): 

 

if color_column is None: # Single line 

sliced_data = data_frame[[values_column]] 

else: 

sliced_data = data_frame[data_frame[color_column] == 

color_value][[values_column]] 

 

density = True if method == 'density' else False 

hist, edges = np.histogram(sliced_data, density=density, bins=bins) 

 

if method == 'mass': 

hist = hist * 1.0 / hist.sum() 

 

histogram_data = pd.DataFrame({ 

'values': hist, 

'min_edge': edges[:-1], 

'max_edge': edges[1:] 

}) 

 

source = self._named_column_data_source( 

histogram_data, series_name=color_value) 

 

color_value = str( 

color_value) if color_value is not None else color_value 

 

if vertical: 

self._plot_with_legend( 

self._chart.figure.quad, 

legend_label=color_value, 

top='values', 

bottom=0, 

left='min_edge', 

right='max_edge', 

source=source, 

fill_color=color, 

line_color=color, 

alpha=.3 

) 

 

else: 

self._plot_with_legend( 

self._chart.figure.quad, 

legend_label=color_value, 

top='max_edge', 

bottom='min_edge', 

left=0, 

right='values', 

source=source, 

fill_color=color, 

line_color=color, 

alpha=.3, 

) 

 

# Set legend defaults if there are multiple series. 

if color_column is not None: 

self._chart.style._apply_settings('legend') 

 

return self._chart 

 

def kde(self, 

data_frame, 

values_column, 

color_column=None, 

color_order=None): 

"""Kernel Density Estimate Plot. 

 

Args: 

data_frame (pandas.DataFrame): Data source for the plot. 

values_column (str): Column of numeric values. 

color_column (str, optional): Column name to group by on 

the color dimension. 

color_order (list, optional): List of values within the 

'color_column' for specific sorting of the colors. 

""" 

# Vertical is unused since the logic is handled 

# by the area chart 

# vertical = self._chart.axes._vertical 

 

if color_column is not None: 

color_values = sorted(data_frame[color_column].unique()) 

else: 

color_values = [None] 

 

data = pd.DataFrame() 

for color_value in color_values: 

if color_column is None: # Single line 

sliced_data = data_frame 

else: 

sliced_data = data_frame[data_frame[color_column] == 

color_value] 

values = sliced_data[values_column] 

 

kde = gaussian_kde(values) 

index = np.linspace(values.min(), values.max(), 300) 

kde_pdf = kde.evaluate(index) 

data = pd.concat( 

[ 

data, 

pd.DataFrame({ 

'x': index, 

'y': kde_pdf, 

'color': color_value 

}) 

], 

axis=0) 

 

color_column = 'color' if color_column is not None else None 

 

PlotNumericXY.area( 

self, 

data, 

'x', 

'y', 

color_column=color_column, 

color_order=color_values, 

stacked=False) 

 

return self._chart 

 

 

class PlotDensityXY(BasePlot): 

"""Plot functions for denxity X & Y: 

 

Methods: 

- hexbin 

""" 

 

def hexbin(self, 

data_frame, 

x_values_column, 

y_values_column, 

size, 

color_palette='Blues', 

reverse_color_order=False, 

orientation='pointytop', 

color_value_range=10 

): 

"""Hexbin. 

 

Args: 

data_frame (pandas.DataFrame): Data source for the plot. 

x_values_column (str): Column of numeric values to bin into tiles. 

y_values_column (str): Column of numeric values to bin into tiles. 

size (float): Bin size for the tiles. 

color_palette (str, chartify.ColorPalette): Color palette to 

apply to the tiles. 

See chartify.color_palettes.show() for available color palettes. 

reverse_color_order (bool): Reverse order of the color palette. 

orientation (str): "pointytop" or "flattop". Whether the hexagonal 

tiles should be oriented with a pointed corner on top, or a 

flat side on top. 

color_value_range (int): The size of the range of colors in 

the color palette. 

A larger color range will result in greater variation 

among the cell colors. 

""" 

if isinstance(color_palette, str): 

color_palette = color_palettes[color_palette] 

if reverse_color_order: 

color_palette = color_palette[::-1] 

color_palette = color_palette.expand_palette(color_value_range) 

color_palette = [c.get_hex_l() for c in color_palette.colors] 

 

# Set the chart aspect ratio otherwise the hexbins won't be symmetric. 

aspect_scale = (self._chart.style.plot_width 

/ self._chart.style.plot_height) 

self._chart.figure.match_aspect = True 

self._chart.figure.aspect_scale = aspect_scale 

self._chart.figure.hexbin( 

data_frame[x_values_column], 

data_frame[y_values_column], 

size=size, 

orientation=orientation, 

aspect_scale=aspect_scale, 

palette=color_palette, 

line_color='white' 

) 

 

return self._chart 

 

 

class PlotMixedTypeXY(BasePlot): 

"""Plot functions for mixed type x & y axes: 

 

Methods: 

- bar 

- bar_stacked 

- lollipop 

- parallel 

""" 

 

def _set_categorical_axis_default_factors(self, vertical, factors): 

"""Reassign the categorical axis with the given factors. 

""" 

if vertical: 

self._chart.figure.x_range.factors = factors 

else: 

self._chart.figure.y_range.factors = factors 

 

def _set_categorical_axis_default_range(self, vertical, data_frame, 

numeric_column): 

"""Set numeric axis range based on the input data. 

""" 

max_value = data_frame[numeric_column].max() 

min_value = data_frame[numeric_column].min() 

 

max_ge_zero = max_value >= 0 

min_ge_zero = min_value >= 0 

 

range_start, range_end = None, None 

if max_ge_zero and min_ge_zero: 

range_start = 0 

elif not max_ge_zero and not min_ge_zero: 

range_end = 0 

 

max_value = max(max_value, 0) 

min_value = min(min_value, 0) 

 

if vertical: 

self._chart.axes.set_yaxis_range(start=range_start, end=range_end) 

self._chart.axes.set_yaxis_tick_format( 

self._axis_format_precision(max_value, min_value)) 

else: 

self._chart.axes.set_xaxis_range(start=range_start, end=range_end) 

self._chart.axes.set_xaxis_tick_format( 

self._axis_format_precision(max_value, min_value)) 

 

@staticmethod 

def _get_bar_width(factors): 

"""Get the bar width based on the number of factors""" 

n_factors = len(factors) 

if n_factors == 1: 

return .3 

elif n_factors == 2: 

return .5 

elif n_factors == 3: 

return .7 

else: 

return .9 

 

def _construct_source(self, 

data_frame, 

categorical_columns, 

numeric_column, 

stack_column=None, 

normalize=False, 

categorical_order_by=None, 

categorical_order_ascending=False, 

color_column=None): 

"""Constructs ColumnDataSource 

 

Returns: 

source: ColumnDataSource 

factors: list of categorical factors 

stack_values: list of stack values 

""" 

# Cast categorical columns to a list. 

if not isinstance(categorical_columns, str): 

categorical_columns = [c for c in categorical_columns] 

else: 

categorical_columns = [categorical_columns] 

 

# Check that there's only one row per grouping 

grouping = categorical_columns[:] 

if stack_column is not None: 

grouping.append(stack_column) 

rows_per_grouping = (data_frame.groupby(grouping).size()) 

max_one_row_per_grouping = all(rows_per_grouping <= 1) 

if not max_one_row_per_grouping: 

raise ValueError( 

"""Each categorical grouping should have at most 1 observation. 

Group the dataframe and aggregate before passing to 

the plot function. 

""") 

 

# Cast stack column to strings 

# Plotting functions will break with non-str types. 

type_map = {} 

if stack_column is not None: 

type_map[stack_column] = str 

# Apply mapping within pivot so original data frame isn't modified. 

source = ( 

pd.pivot_table( 

data_frame.astype(type_map), 

columns=stack_column, 

index=categorical_columns, 

values=numeric_column, 

aggfunc='sum') 

) 

# NA columns break the stacks 

# Might want to make this conditional in the future for parallel plots. 

source = source.fillna(0) 

 

if color_column: 

# Merge color column 

color_df = data_frame.astype(type_map) 

color_df['color_column'] = color_df[color_column].astype(str) 

color_df = color_df.set_index(categorical_columns)['color_column'] 

source = source.join(color_df) 

 

# Normalize values at the grouped levels. 

# Only relevant for stacked objects 

if normalize: 

source = source.div(source.sum(axis=1), axis=0) 

 

order_length = getattr(categorical_order_by, "__len__", None) 

# Sort the categories 

if categorical_order_by == 'values': 

# Recursively sort values within each level of the index. 

row_totals = source.sum(axis=1) 

row_totals.name = 'sum' 

old_index = row_totals.index 

row_totals = row_totals.reset_index() 

row_totals.columns = ['_%s' % col for col in row_totals.columns] 

row_totals.index = old_index 

 

heirarchical_sort_cols = categorical_columns[:] 

for i, _ in enumerate(heirarchical_sort_cols): 

row_totals['level_%s' % i] = (row_totals.groupby( 

heirarchical_sort_cols[:i + 1])['_sum'].transform('sum')) 

row_totals = row_totals.sort_values( 

by=[ 

'level_%s' % i 

for i, _ in enumerate(heirarchical_sort_cols) 

], 

ascending=categorical_order_ascending) 

source = source.reindex(row_totals.index) 

elif categorical_order_by == 'labels': 

source = source.sort_index( 

0, ascending=categorical_order_ascending) 

# Manual sort 

elif order_length is not None: 

source = source.reindex(categorical_order_by, axis='index') 

else: 

raise ValueError( 

"""Must be 'values', 'labels', or a list of values.""") 

 

# Cast all categorical columns to strings 

# Plotting functions will break with non-str types. 

if isinstance(source.index, pd.MultiIndex): 

for level in range(len(source.index.levels)): 

source.index = source.index.set_levels( 

source.index.levels[level].astype(str), level=level) 

else: 

source.index = source.index.astype(str) 

 

factors = source.index 

source = source.reset_index(drop=True) 

stack_values = source.columns 

source = self._named_column_data_source(source, series_name=None) 

source.add(factors, 'factors') 

 

return source, factors, stack_values 

 

def text(self, 

data_frame, 

categorical_columns, 

numeric_column, 

text_column, 

color_column=None, 

color_order=None, 

categorical_order_by='values', 

categorical_order_ascending=False, 

font_size='1em', 

x_offset=0, 

y_offset=0, 

angle=0, 

text_color=None): 

"""Text plot. 

 

Args: 

data_frame (pandas.DataFrame): Data source for the plot. 

categorical_columns (str or list): Column name to plot on 

the categorical axis. 

numeric_column (str): Column name to plot on the numerical axis. 

text_column (str): Column name to plot as text labels. 

color_column (str, optional): Column name to group by on the 

color dimension. 

color_order (list, optional): List of values within the 

'color_column' for specific color sort. 

categorical_order_by (str or array-like, optional): 

Dimension for ordering the categorical axis. Default 'values'. 

- 'values': Order categorical axis by the numerical axis 

values. Default. 

- 'labels': Order categorical axis by the categorical labels. 

- array-like object (list, tuple, np.array): New labels 

to conform the categorical axis to. 

categorical_order_ascending (bool, optional): Sort order of the 

categorical axis. Default False. 

font_size (str, optional): Size of text. 

x_offset (int, optional): # of pixels for horizontal text offset. 

Can be negative. Default: 0. 

y_offset (int, optional): # of pixels for vertical text offset. 

Can be negative. Default: 0. 

angle (int): Degrees from horizontal for text rotation. 

text_color (str): Color name or hex value. 

See chartify.color_palettes.show() for available color names. 

If omitted, will default to the next color in 

the current color palette. 

""" 

vertical = self._chart.axes._vertical 

text_font = self._chart.style._get_settings('text_callout_and_plot')[ 

'font'] 

 

source, factors, _ = self._construct_source( 

data_frame, 

categorical_columns, 

numeric_column, 

categorical_order_by=categorical_order_by, 

categorical_order_ascending=categorical_order_ascending) 

 

if text_color: 

text_color = Color(text_color).get_hex_l() 

colors, color_values = [text_color], [None] 

else: 

colors, color_values = self._get_color_and_order( 

data_frame, color_column, color_order) 

 

self._set_categorical_axis_default_factors(vertical, factors) 

 

if vertical: 

text_align = 'center' 

text_baseline = 'bottom' 

x_value, y_value = 'factors', numeric_column 

y_offset = y_offset - 4 

else: 

y_value, x_value = 'factors', numeric_column 

text_align = 'left' 

text_baseline = 'middle' 

x_offset = x_offset + 10 

 

for color_value, color in zip(color_values, colors): 

 

if color_column is None: # Single series 

sliced_data = data_frame 

else: 

sliced_data = data_frame[data_frame[color_column] == 

color_value] 

 

# Construct a new source based on the sliced data. 

source, _, _ = self._construct_source( 

sliced_data, 

categorical_columns, 

numeric_column, 

categorical_order_by=categorical_order_by, 

categorical_order_ascending=categorical_order_ascending) 

sliced_data = (sliced_data.astype(str) 

.set_index(categorical_columns) 

.reindex(source.data['factors']).reset_index()) 

# Text column isn't in the source so it needs to be added. 

sliced_data['text_column'] = sliced_data[text_column] 

source.add(sliced_data['text_column'], name='text_column') 

 

self._chart.figure.text( 

text='text_column', 

x=x_value, 

y=y_value, 

text_font_size=font_size, 

source=source, 

text_color=color, 

y_offset=y_offset, 

x_offset=x_offset, 

angle=angle, 

angle_units='deg', 

text_align=text_align, 

text_baseline=text_baseline, 

text_font=text_font) 

 

return self._chart 

 

def text_stacked(self, 

data_frame, 

categorical_columns, 

numeric_column, 

stack_column, 

text_column, 

normalize=False, 

stack_order=None, 

categorical_order_by='values', 

categorical_order_ascending=False, 

font_size='1em', 

x_offset=0, 

y_offset=0, 

angle=0, 

text_color=None): 

"""Text plot for use with stacked plots. 

 

Args: 

data_frame (pandas.DataFrame): Data source for the plot. 

categorical_columns (str or list): Column name to plot on 

the categorical axis. 

numeric_column (str): Column name to plot on the numerical axis. 

text_column (str): Column name to plot as text labels. 

Note: Null text values will be omitted from the plot. 

stack_column (str): Column name to group by on the stack dimension. 

normalize (bool, optional): Normalize numeric dimension for 

100% stacked bars. Default False. 

stack_order (list, optional): List of values within the 

'stack_column' dimension for specific stack sort. 

categorical_order_by (str or array-like, optional): 

Dimension for ordering the categorical axis. Default 'values'. 

- 'values': Order categorical axis by the numerical 

axis values. Default. 

- 'labels': Order categorical axis by the categorical labels. 

- array-like object (list, tuple, np.array): New labels 

to conform the categorical axis to. 

categorical_order_ascending (bool, optional): Sort order of the 

categorical axis. Default False. 

font_size (str, optional): Size of text. 

x_offset (int, optional): # of pixels for horizontal text offset. 

Can be negative. Default: 0. 

y_offset (int, optional): # of pixels for vertical text offset. 

Can be negative. Default: 0. 

angle (int): Degrees from horizontal for text rotation. 

text_color (str): Color name or hex value. 

See chartify.color_palettes.show() for available color names. 

If omitted, will default to the next color in 

the current color palette. 

""" 

vertical = self._chart.axes._vertical 

text_font = self._chart.style._get_settings('text_callout_and_plot')[ 

'font'] 

 

source, factors, stack_values = self._construct_source( 

data_frame, 

categorical_columns, 

numeric_column, 

stack_column, 

normalize=normalize, 

categorical_order_by=categorical_order_by, 

categorical_order_ascending=categorical_order_ascending) 

 

if text_color: 

text_color = Color(text_color).get_hex_l() 

if stack_order is None: 

stack_order = sorted(data_frame[stack_column].unique()) 

else: 

# If stack order is set then 

# make sure it includes all the levels. 

if not set(data_frame[stack_column].unique()).issubset( 

set(stack_order)): 

raise ValueError("""Color order must include 

all unique factors of variable `%s`.""" % 

stack_order) 

colors, color_values = [text_color] * len( 

data_frame[stack_column].unique()), stack_order 

else: 

colors, color_values = self._get_color_and_order( 

data_frame, stack_column, stack_order) 

 

self._set_categorical_axis_default_factors(vertical, factors) 

self._set_categorical_axis_default_range(vertical, data_frame, 

numeric_column) 

 

# Set numeric axis format to percentages. 

if normalize: 

if vertical: 

self._chart.axes.set_yaxis_tick_format("0%") 

else: 

self._chart.axes.set_xaxis_tick_format("0%") 

 

text_baseline = 'middle' 

if vertical: 

text_align = 'center' 

else: 

text_align = 'left' 

x_offset = x_offset + 10 

 

cumulative_numeric_value = None 

 

for color_value, color in zip(color_values, colors): 

 

sliced_data = data_frame[(data_frame[stack_column] == color_value)] 

# Reindex to be consistent with the factors. 

type_map = {column: str for column in categorical_columns} 

sliced_data = (sliced_data.astype(type_map) 

.set_index(categorical_columns) 

.reindex(index=factors).reset_index()) 

 

text_values = np.where(sliced_data[text_column].isna(), '', 

sliced_data[text_column].astype(str)) 

 

if cumulative_numeric_value is not None: 

cumulative_numeric_value = ( 

cumulative_numeric_value 

+ source.data[color_value] 

* .5 

) 

else: 

cumulative_numeric_value = source.data[color_value] * .5 

 

if vertical: 

x_value, y_value = factors, cumulative_numeric_value 

else: 

y_value, x_value = factors, cumulative_numeric_value 

 

self._chart.figure.text( 

text=text_values, 

x=x_value, 

y=y_value, 

text_font_size=font_size, 

text_color=color, 

y_offset=y_offset, 

x_offset=x_offset, 

angle=angle, 

angle_units='deg', 

text_align=text_align, 

text_baseline=text_baseline, 

text_font=text_font) 

 

cumulative_numeric_value = ( 

cumulative_numeric_value 

+ source.data[color_value] 

* .5 

) 

 

return self._chart 

 

def bar(self, 

data_frame, 

categorical_columns, 

numeric_column, 

color_column=None, 

color_order=None, 

categorical_order_by='values', 

categorical_order_ascending=False): 

"""Bar chart. 

 

Note: 

To change the orientation set x_axis_type or y_axis_type 

argument of the Chart object. 

 

Args: 

data_frame (pandas.DataFrame): Data source for the plot. 

categorical_columns (str or list): Column name to plot on 

the categorical axis. 

numeric_column (str): Column name to plot on the numerical axis. 

color_column (str, optional): Column name to group by on 

the color dimension. 

color_order (list, optional): List of values within the 

'color_column' for specific color sort. 

categorical_order_by (str or array-like, optional): 

Dimension for ordering the categorical axis. Default 'values'. 

- 'values': Order categorical axis by the numerical 

axis values. Default. 

- 'labels': Order categorical axis by the categorical labels. 

- array-like object (list, tuple, np.array): New labels 

to conform the categorical axis to. 

categorical_order_ascending (bool, optional): Sort order of the 

categorical axis. Default False. 

""" 

vertical = self._chart.axes._vertical 

 

source, factors, _ = self._construct_source( 

data_frame, 

categorical_columns, 

numeric_column, 

categorical_order_by=categorical_order_by, 

categorical_order_ascending=categorical_order_ascending, 

color_column=color_column) 

 

colors, color_values = self._get_color_and_order( 

data_frame, color_column, color_order, categorical_columns) 

 

if color_column is None: 

colors = colors[0] 

 

self._set_categorical_axis_default_factors(vertical, factors) 

self._set_categorical_axis_default_range(vertical, data_frame, 

numeric_column) 

bar_width = self._get_bar_width(factors) 

 

if color_column: 

legend = bokeh.core.properties.field('color_column') 

legend = 'color_column' 

else: 

legend = None 

 

if vertical: 

self._plot_with_legend( 

self._chart.figure.vbar, 

legend_group=legend, 

x='factors', 

width=bar_width, 

top=numeric_column, 

bottom=0, 

line_color='white', 

source=source, 

fill_color=colors, 

) 

 

else: 

 

self._plot_with_legend( 

self._chart.figure.hbar, 

legend_group=legend, 

y='factors', 

height=bar_width, 

right=numeric_column, 

left=0, 

line_color='white', 

source=source, 

fill_color=colors, 

) 

 

# Set legend defaults if there are multiple series. 

if color_column is not None: 

self._chart.style._apply_settings('legend') 

return self._chart 

 

def interval(self, 

data_frame, 

categorical_columns, 

lower_bound_column, 

upper_bound_column, 

middle_column=None, 

categorical_order_by='values', 

categorical_order_ascending=False, 

color='black'): 

"""Interval. 

 

Args: 

data_frame (pandas.DataFrame): Data source for the plot. 

categorical_columns (str or list): Column name to plot on 

the categorical axis. 

lower_bound_column (str): Column name to plot on the 

numerical axis for the lower bound. 

upper_bound_column (str): Column name to plot on the 

numerical axis for the upper bound. 

middle_column (str, optional): Column name to plot on the 

numerical axis for the middle tick. 

categorical_order_by (str or array-like, optional): 

Dimension for ordering the categorical axis. Default 'values'. 

- 'values': Order categorical axis by the numerical 

axis values. Default. 

- 'labels': Order categorical axis by the categorical labels. 

- array-like object (list, tuple, np.array): New labels 

to conform the categorical axis to. 

categorical_order_ascending (bool, optional): Sort order of the 

categorical axis. Default False. 

color (str): Color name or hex value. 

See chartify.color_palettes.show() for available color names. 

""" 

interval_color = Color(color).get_hex_l() 

 

vertical = self._chart.axes._vertical 

 

_, factors, _ = self._construct_source( 

data_frame, 

categorical_columns, 

lower_bound_column, 

categorical_order_by=categorical_order_by, 

categorical_order_ascending=categorical_order_ascending) 

self._set_categorical_axis_default_factors(vertical, factors) 

 

# Set the axis precision 

max_value = max(data_frame[lower_bound_column].max(), 

data_frame[upper_bound_column].max()) 

min_value = min(data_frame[lower_bound_column].min(), 

data_frame[upper_bound_column].min()) 

max_value, min_value = max(max_value, 0), min(min_value, 0) 

if vertical: 

self._chart.axes.set_yaxis_tick_format( 

self._axis_format_precision(max_value, 

min_value) 

) 

else: 

self._chart.axes.set_xaxis_tick_format( 

self._axis_format_precision(max_value, 

min_value) 

) 

 

interval_settings = self._chart.style._get_settings('interval_plot') 

SPACE_BETWEEN_BARS = interval_settings['space_between_bars'] 

MARGIN = interval_settings['margin'] 

BAR_WIDTH = interval_settings['bar_width'] 

SPACE_BETWEEN_CATEGORIES = interval_settings[ 

'space_between_categories'] 

INTERVAL_END_STEM_SIZE = interval_settings['interval_end_stem_size'] 

INTERVAL_MIDPOINT_STEM_SIZE = interval_settings[ 

'interval_midpoint_stem_size'] 

 

def bar_edges(index, category_number): 

"""Return start, midpoint, end edge coordinates""" 

bar_num = index + 1 

start = ( 

bar_num * MARGIN + (bar_num - 1) * MARGIN + (bar_num - 1) * 

(BAR_WIDTH) + SPACE_BETWEEN_BARS * (bar_num - 1) + 

SPACE_BETWEEN_CATEGORIES * (category_number - 1)) 

midpoint = start + BAR_WIDTH / 2. 

end = start + BAR_WIDTH 

return (start, midpoint, end) 

 

aggregate_columns = [lower_bound_column, upper_bound_column] 

if middle_column is not None: 

aggregate_columns.append(middle_column) 

# Categorical_columns to List 

if not isinstance(categorical_columns, str): 

categorical_columns = [c for c in categorical_columns] 

else: 

categorical_columns = [categorical_columns] 

# Cast categorical columns to str to prevent dates from breaking 

type_map = {column: str for column in categorical_columns} 

values = (data_frame.astype(type_map) 

.groupby(categorical_columns)[aggregate_columns].sum() 

.reindex(factors).reset_index()) 

# Need to keep track of changes to categorical columns 

# To calculate spacing between values 

values['new_heirarchy'] = False 

if len(categorical_columns) > 1: 

for col in categorical_columns[:-1]: 

values['new_column'] = values[col] != values[col].shift(1) 

values['new_heirarchy'] = values[[ 

'new_heirarchy', 'new_column' 

]].max(axis=1) 

values['category_number'] = values['new_heirarchy'].cumsum() 

else: 

values['category_number'] = 1 

for index, row in values.iterrows(): 

bar_midpoint = bar_edges(index, row['category_number'])[1] 

if vertical: 

# Vertical line 

self._chart.figure.segment( 

bar_midpoint, 

row[lower_bound_column], 

bar_midpoint, 

row[upper_bound_column], 

color=interval_color) 

# Top 

self._chart.figure.segment( 

bar_midpoint - INTERVAL_END_STEM_SIZE, 

row[upper_bound_column], 

bar_midpoint + INTERVAL_END_STEM_SIZE, 

row[upper_bound_column], 

color=interval_color) 

# Bottom 

self._chart.figure.segment( 

bar_midpoint - INTERVAL_END_STEM_SIZE, 

row[lower_bound_column], 

bar_midpoint + INTERVAL_END_STEM_SIZE, 

row[lower_bound_column], 

color=interval_color) 

# Middle 

if middle_column is not None: 

self._chart.figure.segment( 

bar_midpoint - INTERVAL_MIDPOINT_STEM_SIZE, 

row[middle_column], 

bar_midpoint + INTERVAL_MIDPOINT_STEM_SIZE, 

row[middle_column], 

color=interval_color) 

else: 

# Horizontal line 

self._chart.figure.segment( 

row[lower_bound_column], 

bar_midpoint, 

row[upper_bound_column], 

bar_midpoint, 

color=interval_color) 

# Left 

self._chart.figure.segment( 

row[lower_bound_column], 

bar_midpoint - INTERVAL_END_STEM_SIZE, 

row[lower_bound_column], 

bar_midpoint + INTERVAL_END_STEM_SIZE, 

color=interval_color) 

# Right 

self._chart.figure.segment( 

row[upper_bound_column], 

bar_midpoint - INTERVAL_END_STEM_SIZE, 

row[upper_bound_column], 

bar_midpoint + INTERVAL_END_STEM_SIZE, 

color=interval_color) 

# Middle 

if middle_column is not None: 

self._chart.figure.segment( 

row[middle_column], 

bar_midpoint - INTERVAL_MIDPOINT_STEM_SIZE, 

row[middle_column], 

bar_midpoint + INTERVAL_MIDPOINT_STEM_SIZE, 

color=interval_color) 

return self._chart 

 

def bar_stacked(self, 

data_frame, 

categorical_columns, 

numeric_column, 

stack_column, 

normalize=False, 

stack_order=None, 

categorical_order_by='values', 

categorical_order_ascending=False): 

"""Plot stacked bar chart. 

 

Note: 

- To change the orientation set x_axis_type or y_axis_type 

argument of the Chart object. 

- Stacked numeric values must be all positive or all negative. 

To plot both positive and negative values on the same chart 

call this method twice. Once for the positive values and 

once for the negative values. 

 

Args: 

data_frame (pandas.DataFrame): Data source for the plot. 

categorical_columns (str or list): Column name to plot on 

the categorical axis. 

numeric_column (str): Column name to plot on the numerical axis. 

stack_column (str): Column name to group by on the stack dimension. 

normalize (bool, optional): Normalize numeric dimension for 

100% stacked bars. Default False. 

stack_order (list, optional): List of values within the 

'stack_column' dimension for specific stack sort. 

categorical_order_by (str or array-like, optional): 

Dimension for ordering the categorical axis. Default 'values'. 

- 'values': Order categorical axis by the numerical 

axis values. Default. 

- 'labels': Order categorical axis by the categorical labels. 

- array-like object (list, tuple, np.array): New labels 

to conform the categorical axis to. 

categorical_order_ascending (bool, optional): Sort order 

of the categorical axis. Default False. 

""" 

 

vertical = self._chart.axes._vertical 

 

source, factors, stack_values = self._construct_source( 

data_frame, 

categorical_columns, 

numeric_column, 

stack_column, 

normalize=normalize, 

categorical_order_by=categorical_order_by, 

categorical_order_ascending=categorical_order_ascending) 

 

colors, _ = self._get_color_and_order(data_frame, stack_column, 

stack_order) 

if stack_column is None: 

colors = colors[0] 

 

self._set_categorical_axis_default_factors(vertical, factors) 

self._set_categorical_axis_default_range(vertical, data_frame, 

numeric_column) 

bar_width = self._get_bar_width(factors) 

# Set numeric axis format to percentages. 

if normalize: 

if vertical: 

self._chart.axes.set_yaxis_tick_format("0%") 

else: 

self._chart.axes.set_xaxis_tick_format("0%") 

 

if stack_order is not None: 

if not set(stack_values).issubset(set(stack_order)): 

raise ValueError("""Stack order must include all distinct 

values of the stack column `%s` 

""" % (stack_column)) 

stack_values = stack_order 

 

legend = [str(value) for value in stack_values] 

 

if vertical: 

self._plot_with_legend( 

self._chart.figure.vbar_stack, 

legend_label=legend, 

stackers=stack_values, 

x='factors', 

width=bar_width, 

line_color='white', 

source=source, 

fill_color=colors, 

) 

 

else: 

self._plot_with_legend( 

self._chart.figure.hbar_stack, 

legend_label=legend, 

stackers=stack_values, 

y='factors', 

height=bar_width, 

line_color='white', 

source=source, 

fill_color=colors, 

) 

 

self._chart.style._apply_settings('legend') 

# Reverse order of vertical legends to ensure that the order 

# is consistent with the stack order. 

self._chart._reverse_vertical_legend = True 

 

return self._chart 

 

def lollipop(self, 

data_frame, 

categorical_columns, 

numeric_column, 

color_column=None, 

color_order=None, 

categorical_order_by='values', 

categorical_order_ascending=False): 

"""Lollipop chart. 

 

Note: 

To change the orientation set x_axis_type or y_axis_type 

argument of the Chart object. 

 

Args: 

data_frame (pandas.DataFrame): Data source for the plot. 

categorical_columns (str or list): Column name to plot on 

the categorical axis. 

numeric_column (str): Column name to plot on the numerical axis. 

color_column (str, optional): Column name to group by on 

the color dimension. 

color_order (list, optional): 

List of values within the 'color_column' for 

specific color sort. 

categorical_order_by (str or array-like, optional): 

Dimension for ordering the categorical axis. Default 'values'. 

- 'values': Order categorical axis by the numerical axis values. 

- 'labels': Order categorical axis by the categorical labels. 

- array-like object (list, tuple, np.array): New labels 

to conform the categorical axis to. 

categorical_order_ascending (bool, optional): 

Sort order of the categorical axis. Default False. 

""" 

 

vertical = self._chart.axes._vertical 

 

source, factors, _ = self._construct_source( 

data_frame, 

categorical_columns, 

numeric_column, 

categorical_order_by=categorical_order_by, 

categorical_order_ascending=categorical_order_ascending, 

color_column=color_column) 

 

colors, color_values = self._get_color_and_order( 

data_frame, color_column, color_order, categorical_columns) 

if color_column is None: 

colors = colors[0] 

 

self._set_categorical_axis_default_factors(vertical, factors) 

self._set_categorical_axis_default_range(vertical, data_frame, 

numeric_column) 

 

if color_column: 

legend = 'color_column' 

else: 

legend = None 

 

if vertical: 

self._chart.figure.segment( 

'factors', 

0, 

'factors', 

numeric_column, 

line_width=2, 

line_color=colors, 

source=source) 

 

self._plot_with_legend( 

self._chart.figure.circle, 

legend_group=legend, 

x='factors', 

y=numeric_column, 

size=10, 

fill_color=colors, 

line_color=colors, 

line_width=3, 

source=source, 

) 

 

else: 

self._chart.figure.segment( 

0, 

'factors', 

numeric_column, 

'factors', 

line_width=2, 

line_color=colors, 

source=source) 

 

self._plot_with_legend( 

self._chart.figure.circle, 

legend_group=legend, 

x=numeric_column, 

y='factors', 

size=10, 

fill_color=colors, 

line_color=colors, 

line_width=3, 

source=source, 

) 

 

# Set legend defaults if there are multiple series. 

if color_column is not None: 

self._chart.style._apply_settings('legend') 

 

return self._chart 

 

def parallel(self, 

data_frame, 

categorical_columns, 

numeric_column, 

color_column=None, 

color_order=None, 

categorical_order_by='values', 

categorical_order_ascending=False, 

line_dash='solid', 

line_width=4, 

alpha=1.0 

): 

"""Parallel coordinate plot. 

 

Args: 

data_frame (pandas.DataFrame): Data source for the plot. 

categorical_columns (str or list): Column name to plot on 

the categorical axis. 

numeric_column (str): Column name to plot on the numerical axis. 

color_column (str, optional): Column name to group by on 

the color dimension. 

color_order (list, optional): List of values within the 

'color_column' for specific color sort. 

categorical_order_by (str or array-like, optional): 

Dimension for ordering the categorical axis. Default 'values'. 

- 'values': Order categorical axis by the numerical axis values. 

- 'labels': Order categorical axis by the categorical labels. 

- array-like object (list, tuple, np.array): New labels 

to conform the categorical axis to. 

categorical_order_ascending (bool, optional): 

Sort order of the categorical axis. Default False. 

line_dash (str, optional): Dash style for the line. One of: 

- 'solid' 

- 'dashed' 

- 'dotted' 

- 'dotdash' 

- 'dashdot' 

line_width (int, optional): Width of the line 

alpha (float): Alpha value 

""" 

settings = self._chart.style._get_settings('line_plot') 

line_cap = settings['line_cap'] 

line_join = settings['line_join'] 

 

vertical = self._chart.axes._vertical 

 

source, factors, _ = self._construct_source( 

data_frame, 

categorical_columns, 

numeric_column, 

# Each color has its own stack for parallel plots. 

# This causes each color to appear as its own column. 

stack_column=color_column, 

categorical_order_by=categorical_order_by, 

categorical_order_ascending=categorical_order_ascending) 

 

colors, color_values = self._get_color_and_order( 

data_frame, color_column, color_order) 

 

self._set_categorical_axis_default_factors(vertical, factors) 

self._set_numeric_axis_default_format(data_frame, 

numeric_column, 

numeric_column) 

 

for color_value, color in zip(color_values, colors): 

 

if color_column is None: # Single series 

color_value = numeric_column 

legend = None 

else: 

legend = str(color_value) 

 

if vertical: 

x_value, y_value = 'factors', str(color_value) 

else: 

y_value, x_value = 'factors', str(color_value) 

 

self._plot_with_legend( 

self._chart.figure.line, 

legend_label=legend, 

x=x_value, 

y=y_value, 

source=source, 

line_width=line_width, 

color=color, 

line_join=line_join, 

line_cap=line_cap, 

line_dash=line_dash, 

alpha=alpha) 

 

# Set legend defaults if there are multiple series. 

if color_column is not None: 

self._chart.style._apply_settings('legend') 

 

def scatter(self, 

data_frame, 

categorical_columns, 

numeric_column, 

size_column=None, 

color_column=None, 

color_order=None, 

categorical_order_by='count', 

categorical_order_ascending=False, 

alpha=1.0, 

marker='circle'): 

"""Scatter chart. 

 

Note: 

To change the orientation set x_axis_type or y_axis_type 

argument of the Chart object. 

 

Args: 

data_frame (pandas.DataFrame): Data source for the plot. 

categorical_columns (str or list): Column name to plot on 

the categorical axis. 

numeric_column (str): Column name to plot on the numerical axis. 

size_column (str, optional): Column name of numerical values 

to plot on the size dimension. 

color_column (str, optional): Column name to group by on 

the color dimension. 

color_order (list, optional): 

List of values within the 'color_column' for 

specific color sort. 

categorical_order_by (str or array-like, optional): 

Dimension for ordering the categorical axis. Default 'count'. 

- 'count': Order categorical axis by the count of values. 

- 'labels': Order categorical axis by the categorical labels. 

- array-like object (list, tuple, np.array): New labels 

to conform the categorical axis to. 

categorical_order_ascending (bool, optional): 

Sort order of the categorical axis. Default False. 

alpha (float): Alpha value. 

marker (str): marker type. Valid types: 

'asterisk', 'circle', 'circle_cross', 'circle_x', 'cross', 

'diamond', 'diamond_cross', 'hex', 'inverted_triangle', 

'square', 'square_x', 'square_cross', 'triangle', 

'x', '*', '+', 'o', 'ox', 'o+' 

""" 

vertical = self._chart.axes._vertical 

 

if size_column is None: 

size_column = 15 

 

axis_factors = data_frame.groupby(categorical_columns).size() 

 

order_length = getattr(categorical_order_by, "__len__", None) 

if categorical_order_by == 'labels': 

axis_factors = axis_factors.sort_index( 

ascending=categorical_order_ascending).index 

elif categorical_order_by == 'count': 

axis_factors = axis_factors.sort_values( 

ascending=categorical_order_ascending).index 

# User-specified order. 

elif order_length is not None: 

axis_factors = categorical_order_by 

else: 

raise ValueError( 

"""Must be 'count', 'labels', or a list of values.""") 

 

colors, color_values = self._get_color_and_order( 

data_frame, color_column, color_order) 

# Apply factors to the axis. 

self._set_categorical_axis_default_factors(vertical, axis_factors) 

 

for color_value, color in zip(color_values, colors): 

if color_column is None: # Single series 

color_value = numeric_column 

legend = None 

sliced_data = data_frame 

else: 

legend = bokeh.core.properties.value(str(color_value)) 

sliced_data = data_frame[data_frame[color_column] == 

color_value] 

# Filter to only relevant columns. 

data_factors = sliced_data.set_index(categorical_columns).index 

sliced_data = ( 

sliced_data[ 

[col for col in sliced_data.columns 

if col in ( 

numeric_column, size_column)]]) 

source = self._named_column_data_source( 

sliced_data, series_name=color_value) 

source.add(data_factors, 'factors') 

 

if vertical: 

x_value, y_value = 'factors', numeric_column 

else: 

y_value, x_value = 'factors', numeric_column 

 

self._plot_with_legend( 

self._chart.figure.scatter, 

legend_label=legend, 

x=x_value, 

y=y_value, 

size=size_column, 

fill_color=color, 

line_color=color, 

source=source, 

marker=marker, 

alpha=alpha 

) 

 

# Set legend defaults if there are multiple series. 

if color_column is not None: 

self._chart.style._apply_settings('legend') 

 

return self._chart