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

""" 

Contour Plots 

""" 

 

#***************************************************************************** 

# Copyright (C) 2006 Alex Clemesha <clemesha@gmail.com>, 

# William Stein <wstein@gmail.com>, 

# 2008 Mike Hansen <mhansen@gmail.com>, 

# 

# Distributed under the terms of the GNU General Public License (GPL) 

# 

# This code is distributed in the hope that it will be useful, 

# but WITHOUT ANY WARRANTY; without even the implied warranty of 

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 

# General Public License for more details. 

# 

# The full text of the GPL is available at: 

# 

# http://www.gnu.org/licenses/ 

#***************************************************************************** 

from sage.plot.primitive import GraphicPrimitive 

from sage.misc.decorators import options, suboptions 

from sage.plot.colors import rgbcolor, get_cmap 

from sage.arith.srange import xsrange 

import operator 

 

 

class ContourPlot(GraphicPrimitive): 

""" 

Primitive class for the contour plot graphics type. See 

``contour_plot?`` for help actually doing contour plots. 

 

INPUT: 

 

- ``xy_data_array`` - list of lists giving evaluated values of the function 

on the grid 

 

- ``xrange`` - tuple of 2 floats indicating range for horizontal direction 

 

- ``yrange`` - tuple of 2 floats indicating range for vertical direction 

 

- ``options`` - dict of valid plot options to pass to constructor 

 

EXAMPLES: 

 

Note this should normally be used indirectly via ``contour_plot``:: 

 

sage: from sage.plot.contour_plot import ContourPlot 

sage: C = ContourPlot([[1,3],[2,4]], (1,2), (2,3), options={}) 

sage: C 

ContourPlot defined by a 2 x 2 data grid 

sage: C.xrange 

(1, 2) 

 

TESTS: 

 

We test creating a contour plot:: 

 

sage: x,y = var('x,y') 

sage: contour_plot(x^2-y^3+10*sin(x*y), (x,-4,4), (y,-4,4), 

....: plot_points=121, cmap='hsv') 

Graphics object consisting of 1 graphics primitive 

""" 

def __init__(self, xy_data_array, xrange, yrange, options): 

""" 

Initializes base class ContourPlot. 

 

EXAMPLES:: 

 

sage: x,y = var('x,y') 

sage: C = contour_plot(x^2-y^3+10*sin(x*y), (x,-4,4), (y,-4,4), 

....: plot_points=121, cmap='hsv') 

sage: C[0].xrange 

(-4.0, 4.0) 

sage: C[0].options()['plot_points'] 

121 

""" 

self.xrange = xrange 

self.yrange = yrange 

self.xy_data_array = xy_data_array 

self.xy_array_row = len(xy_data_array) 

self.xy_array_col = len(xy_data_array[0]) 

GraphicPrimitive.__init__(self, options) 

 

def get_minmax_data(self): 

""" 

Returns a dictionary with the bounding box data. 

 

EXAMPLES:: 

 

sage: x,y = var('x,y') 

sage: f(x,y) = x^2 + y^2 

sage: d = contour_plot(f, (3,6), (3,6))[0].get_minmax_data() 

sage: d['xmin'] 

3.0 

sage: d['ymin'] 

3.0 

""" 

from sage.plot.plot import minmax_data 

return minmax_data(self.xrange, self.yrange, dict=True) 

 

def _allowed_options(self): 

""" 

Return the allowed options for the ContourPlot class. 

 

EXAMPLES:: 

 

sage: x,y = var('x,y') 

sage: C = contour_plot(x^2 - y^2, (x,-2,2), (y,-2,2)) 

sage: isinstance(C[0]._allowed_options(), dict) 

True 

""" 

return {'plot_points': 'How many points to use for plotting precision', 

'cmap': """the name of a predefined colormap, 

a list of colors, or an instance of a 

matplotlib Colormap. Type: import matplotlib.cm; 

matplotlib.cm.datad.keys() 

for available colormap names.""", 

'colorbar': "Include a colorbar indicating the levels", 

'colorbar_options': "a dictionary of options for colorbars", 

'fill': 'Fill contours or not', 

'legend_label': 'The label for this item in the legend.', 

'contours': """Either an integer specifying the number of 

contour levels, or a sequence of numbers giving 

the actual contours to use.""", 

'linewidths': 'the width of the lines to be plotted', 

'linestyles': 'the style of the lines to be plotted', 

'labels': 'show line labels or not', 

'label_options': 'a dictionary of options for the labels', 

'zorder': 'The layer level in which to draw'} 

 

def _repr_(self): 

""" 

String representation of ContourPlot primitive. 

 

EXAMPLES:: 

 

sage: x,y = var('x,y') 

sage: C = contour_plot(x^2 - y^2, (x,-2,2), (y,-2,2)) 

sage: c = C[0]; c 

ContourPlot defined by a 100 x 100 data grid 

""" 

return "ContourPlot defined by a %s x %s data grid"%(self.xy_array_row, self.xy_array_col) 

 

def _render_on_subplot(self, subplot): 

""" 

TESTS: 

 

A somewhat random plot, but fun to look at:: 

 

sage: x,y = var('x,y') 

sage: contour_plot(x^2 - y^3 + 10*sin(x*y), (x,-4,4), (y,-4,4), 

....: plot_points=121, cmap='hsv') 

Graphics object consisting of 1 graphics primitive 

""" 

from sage.rings.integer import Integer 

options = self.options() 

fill = options['fill'] 

contours = options['contours'] 

if 'cmap' in options: 

cmap = get_cmap(options['cmap']) 

elif fill or contours is None: 

cmap = get_cmap('gray') 

else: 

if isinstance(contours, (int, Integer)): 

cmap = get_cmap([(i,i,i) for i in xsrange(0,1,1/contours)]) 

else: 

l = Integer(len(contours)) 

cmap = get_cmap([(i,i,i) for i in xsrange(0,1,1/l)]) 

 

x0, x1 = float(self.xrange[0]), float(self.xrange[1]) 

y0, y1 = float(self.yrange[0]), float(self.yrange[1]) 

 

if isinstance(contours, (int, Integer)): 

contours = int(contours) 

 

CSF = None 

if fill: 

if contours is None: 

CSF = subplot.contourf(self.xy_data_array, cmap=cmap, 

extent=(x0, x1, y0, y1)) 

else: 

CSF = subplot.contourf(self.xy_data_array, contours, cmap=cmap, 

extent=(x0, x1, y0, y1), extend='both') 

 

linewidths = options.get('linewidths', None) 

if isinstance(linewidths, (int, Integer)): 

linewidths = int(linewidths) 

elif isinstance(linewidths, (list, tuple)): 

linewidths = tuple(int(x) for x in linewidths) 

 

from sage.plot.misc import get_matplotlib_linestyle 

linestyles = options.get('linestyles', None) 

if isinstance(linestyles, (list, tuple)): 

linestyles = [get_matplotlib_linestyle(i, 'long') for i in linestyles] 

else: 

linestyles = get_matplotlib_linestyle(linestyles, 'long') 

if contours is None: 

CS = subplot.contour(self.xy_data_array, cmap=cmap, 

extent=(x0, x1, y0, y1), 

linewidths=linewidths, linestyles=linestyles) 

else: 

CS = subplot.contour(self.xy_data_array, contours, cmap=cmap, 

extent=(x0, x1, y0, y1), 

linewidths=linewidths, linestyles=linestyles) 

if options.get('labels', False): 

label_options = options['label_options'] 

label_options['fontsize'] = int(label_options['fontsize']) 

if fill and label_options is None: 

label_options['inline'] = False 

subplot.clabel(CS, **label_options) 

if options.get('colorbar', False): 

colorbar_options = options['colorbar_options'] 

from matplotlib import colorbar 

cax, kwds = colorbar.make_axes_gridspec(subplot, **colorbar_options) 

if CSF is None: 

cb = colorbar.Colorbar(cax, CS, **kwds) 

else: 

cb = colorbar.Colorbar(cax, CSF, **kwds) 

cb.add_lines(CS) 

 

 

@suboptions('colorbar', orientation='vertical', format=None, spacing=None) 

@suboptions('label', fontsize=9, colors='blue', inline=None, inline_spacing=3, 

fmt="%1.2f") 

@options(plot_points=100, fill=True, contours=None, linewidths=None, 

linestyles=None, labels=False, frame=True, axes=False, colorbar=False, 

legend_label=None, aspect_ratio=1, region=None) 

def contour_plot(f, xrange, yrange, **options): 

r""" 

``contour_plot`` takes a function of two variables, `f(x,y)` 

and plots contour lines of the function over the specified 

``xrange`` and ``yrange`` as demonstrated below. 

 

``contour_plot(f, (xmin,xmax), (ymin,ymax), ...)`` 

 

INPUT: 

 

- ``f`` -- a function of two variables 

 

- ``(xmin,xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple 

``(x,xmin,xmax)`` 

 

- ``(ymin,ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple 

``(y,ymin,ymax)`` 

 

The following inputs must all be passed in as named parameters: 

 

- ``plot_points`` -- integer (default: 100); number of points to plot 

in each direction of the grid. For old computers, 25 is fine, but 

should not be used to verify specific intersection points. 

 

- ``fill`` -- bool (default: ``True``), whether to color in the area 

between contour lines 

 

- ``cmap`` -- a colormap (default: ``'gray'``), the name of 

a predefined colormap, a list of colors or an instance of a matplotlib 

Colormap. Type: ``import matplotlib.cm; matplotlib.cm.datad.keys()`` 

for available colormap names. 

 

- ``contours`` -- integer or list of numbers (default: ``None``): 

If a list of numbers is given, then this specifies the contour levels 

to use. If an integer is given, then this many contour lines are 

used, but the exact levels are determined automatically. If ``None`` 

is passed (or the option is not given), then the number of contour 

lines is determined automatically, and is usually about 5. 

 

- ``linewidths`` -- integer or list of integer (default: None), if 

a single integer all levels will be of the width given, 

otherwise the levels will be plotted with the width in the order 

given. If the list is shorter than the number of contours, then 

the widths will be repeated cyclically. 

 

- ``linestyles`` -- string or list of strings (default: None), the 

style of the lines to be plotted, one of: ``"solid"``, ``"dashed"``, 

``"dashdot"``, ``"dotted"``, respectively ``"-"``, ``"--"``, 

``"-."``, ``":"``. If the list is shorter than the number of 

contours, then the styles will be repeated cyclically. 

 

- ``labels`` -- boolean (default: False) Show level labels or not. 

 

The following options are to adjust the style and placement of 

labels, they have no effect if no labels are shown. 

 

- ``label_fontsize`` -- integer (default: 9), the font size of 

the labels. 

 

- ``label_colors`` -- string or sequence of colors (default: 

None) If a string, gives the name of a single color with which 

to draw all labels. If a sequence, gives the colors of the 

labels. A color is a string giving the name of one or a 

3-tuple of floats. 

 

- ``label_inline`` -- boolean (default: False if fill is True, 

otherwise True), controls whether the underlying contour is 

removed or not. 

 

- ``label_inline_spacing`` -- integer (default: 3), When inline, 

this is the amount of contour that is removed from each side, 

in pixels. 

 

- ``label_fmt`` -- a format string (default: "%1.2f"), this is 

used to get the label text from the level. This can also be a 

dictionary with the contour levels as keys and corresponding 

text string labels as values. It can also be any callable which 

returns a string when called with a numeric contour level. 

 

- ``colorbar`` -- boolean (default: False) Show a colorbar or not. 

 

The following options are to adjust the style and placement of 

colorbars. They have no effect if a colorbar is not shown. 

 

- ``colorbar_orientation`` -- string (default: 'vertical'), 

controls placement of the colorbar, can be either 'vertical' 

or 'horizontal' 

 

- ``colorbar_format`` -- a format string, this is used to format 

the colorbar labels. 

 

- ``colorbar_spacing`` -- string (default: 'proportional'). If 

'proportional', make the contour divisions proportional to 

values. If 'uniform', space the colorbar divisions uniformly, 

without regard for numeric values. 

 

- ``legend_label`` -- the label for this item in the legend 

 

- ``region`` - (default: None) If region is given, it must be a function 

of two variables. Only segments of the surface where region(x,y) 

returns a number >0 will be included in the plot. 

 

EXAMPLES: 

 

Here we plot a simple function of two variables. Note that 

since the input function is an expression, we need to explicitly 

declare the variables in 3-tuples for the range:: 

 

sage: x,y = var('x,y') 

sage: contour_plot(cos(x^2 + y^2), (x,-4,4), (y,-4,4)) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

g = contour_plot(cos(x**2 + y**2), (x,-4,4), (y,-4,4)) 

sphinx_plot(g) 

 

Here we change the ranges and add some options:: 

 

sage: x,y = var('x,y') 

sage: contour_plot((x^2) * cos(x*y), (x,-10,5), (y,-5,5), fill=False, plot_points=150) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

g = contour_plot((x**2) * cos(x*y), (x,-10,5), (y,-5,5), fill=False, plot_points=150) 

sphinx_plot(g) 

 

An even more complicated plot:: 

 

sage: x,y = var('x,y') 

sage: contour_plot(sin(x^2+y^2) * cos(x) * sin(y), (x,-4,4), (y,-4,4), plot_points=150) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

g = contour_plot(sin(x**2+y**2) * cos(x) * sin(y), (x,-4,4), (y,-4,4),plot_points=150) 

sphinx_plot(g) 

 

Some elliptic curves, but with symbolic endpoints. In the first 

example, the plot is rotated 90 degrees because we switch the 

variables `x`, `y`:: 

 

sage: x,y = var('x,y') 

sage: contour_plot(y^2 + 1 - x^3 - x, (y,-pi,pi), (x,-pi,pi)) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

g = contour_plot(y**2 + 1 - x**3 - x, (y,-pi,pi), (x,-pi,pi)) 

sphinx_plot(g) 

 

:: 

 

sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi)) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

g = contour_plot(y**2 + 1 - x**3 - x, (x,-pi,pi), (y,-pi,pi)) 

sphinx_plot(g) 

 

We can play with the contour levels:: 

 

sage: x,y = var('x,y') 

sage: f(x,y) = x^2 + y^2 

sage: contour_plot(f, (-2,2), (-2,2)) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

def f(x,y): return x**2 + y**2 

g = contour_plot(f, (-2,2), (-2,2)) 

sphinx_plot(g) 

 

:: 

 

sage: contour_plot(f, (-2,2), (-2,2), contours=2, cmap=[(1,0,0), (0,1,0), (0,0,1)]) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

def f(x,y): return x**2 + y**2 

g = contour_plot(f, (-2, 2), (-2, 2), contours=2, cmap=[(1,0,0), (0,1,0), (0,0,1)]) 

sphinx_plot(g) 

 

:: 

 

sage: contour_plot(f, (-2,2), (-2,2), 

....: contours=(0.1,1.0,1.2,1.4), cmap='hsv') 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

def f(x,y): return x**2 + y**2 

g = contour_plot(f, (-2,2), (-2,2), contours=(0.1,1.0,1.2,1.4), cmap='hsv') 

sphinx_plot(g) 

 

:: 

 

sage: contour_plot(f, (-2,2), (-2,2), contours=(1.0,), fill=False) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

def f(x,y): return x**2 + y**2 

g = contour_plot(f, (-2,2), (-2,2), contours=(1.0,), fill=False) 

sphinx_plot(g) 

 

:: 

 

sage: contour_plot(x - y^2, (x,-5,5), (y,-3,3), contours=[-4,0,1]) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

g = contour_plot(x - y**2, (x,-5,5), (y,-3,3), contours=[-4,0,1]) 

sphinx_plot(g) 

 

We can change the style of the lines:: 

 

sage: contour_plot(f, (-2,2), (-2,2), fill=False, linewidths=10) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

def f(x,y): return x**2 + y**2 

g = contour_plot(f, (-2,2), (-2,2), fill=False, linewidths=10) 

sphinx_plot(g) 

 

 

:: 

 

sage: contour_plot(f, (-2,2), (-2,2), fill=False, linestyles='dashdot') 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

def f(x,y): return x**2 + y**2 

g = contour_plot(f, (-2,2), (-2,2), fill=False, linestyles='dashdot') 

sphinx_plot(g) 

 

:: 

 

sage: P = contour_plot(x^2 - y^2, (x,-3,3), (y,-3,3), 

....: contours=[0,1,2,3,4], linewidths=[1,5], 

....: linestyles=['solid','dashed'], fill=False) 

sage: P 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

P = contour_plot(x**2 - y**2, (x,-3,3), (y,-3,3), 

contours=[0,1,2,3,4], linewidths=[1,5], 

linestyles=['solid','dashed'], fill=False) 

sphinx_plot(P) 

 

:: 

 

sage: P = contour_plot(x^2 - y^2, (x,-3,3), (y,-3,3), 

....: contours=[0,1,2,3,4], linewidths=[1,5], 

....: linestyles=['solid','dashed']) 

sage: P 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

P = contour_plot(x**2 - y**2, (x,-3,3), (y,-3,3), 

contours=[0,1,2,3,4], linewidths=[1,5], 

linestyles=['solid','dashed']) 

sphinx_plot(P) 

 

:: 

 

sage: P = contour_plot(x^2 - y^2, (x,-3,3), (y,-3,3), 

....: contours=[0,1,2,3,4], linewidths=[1,5], 

....: linestyles=['-',':']) 

sage: P 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

P = contour_plot(x**2 - y**2, (x,-3,3), (y,-3,3), 

contours=[0,1,2,3,4], linewidths=[1,5], 

linestyles=['-',':']) 

sphinx_plot(P) 

 

We can add labels and play with them:: 

 

sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), 

....: fill=False, cmap='hsv', labels=True) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

P = contour_plot(y**2 + 1 - x**3 - x, (x,-pi,pi), (y,-pi,pi), 

fill=False, cmap='hsv', labels=True) 

sphinx_plot(P) 

 

:: 

 

sage: P=contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), 

....: fill=False, cmap='hsv', 

....: labels=True, label_fmt="%1.0f", 

....: label_colors='black') 

sage: P 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

P=contour_plot(y**2 + 1 - x**3 - x, (x,-pi,pi), (y,-pi,pi), 

fill=False, cmap='hsv', 

labels=True, label_fmt="%1.0f", 

label_colors='black') 

sphinx_plot(P) 

 

:: 

 

sage: P = contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), 

....: fill=False, cmap='hsv', labels=True, 

....: contours=[-4,0,4], 

....: label_fmt={-4:"low", 0:"medium", 4: "hi"}, 

....: label_colors='black') 

sage: P 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

P = contour_plot(y**2 + 1 - x**3 - x, (x,-pi,pi), (y,-pi,pi), 

fill=False, cmap='hsv', labels=True, 

contours=[-4,0,4], 

label_fmt={-4:"low", 0:"medium", 4: "hi"}, 

label_colors='black') 

sphinx_plot(P) 

 

:: 

 

sage: P = contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), 

....: fill=False, cmap='hsv', labels=True, 

....: contours=[-4,0,4], label_fmt=lambda x: "$z=%s$"%x, 

....: label_colors='black', label_inline=True, 

....: label_fontsize=12) 

sage: P 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

P = contour_plot(y**2 + 1 - x**3 - x, (x,-pi,pi), (y,-pi,pi), 

fill=False, cmap='hsv', labels=True, 

contours=[-4,0,4], label_fmt=lambda x: "$z=%s$"%x, 

label_colors='black', label_inline=True, 

label_fontsize=12) 

sphinx_plot(P) 

 

:: 

 

sage: P = contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), 

....: fill=False, cmap='hsv', labels=True, 

....: label_fontsize=18) 

sage: P 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

P = contour_plot(y**2 + 1 - x**3 - x, (x,-pi,pi), (y,-pi,pi), 

fill=False, cmap='hsv', labels=True, 

label_fontsize=18) 

sphinx_plot(P) 

 

:: 

 

sage: P = contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), 

....: fill=False, cmap='hsv', labels=True, 

....: label_inline_spacing=1) 

sage: P 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

P = contour_plot(y**2 + 1 - x**3 - x, (x,-pi,pi), (y,-pi,pi), 

fill=False, cmap='hsv', labels=True, 

label_inline_spacing=1) 

sphinx_plot(P) 

 

:: 

 

sage: P = contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), 

....: fill=False, cmap='hsv', labels=True, 

....: label_inline=False) 

sage: P 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

P = contour_plot(y**2 + 1 - x**3 - x, (x,-pi,pi), (y,-pi,pi), 

fill=False, cmap='hsv', labels=True, 

label_inline=False) 

sphinx_plot(P) 

 

We can change the color of the labels if so desired:: 

 

sage: contour_plot(f, (-2,2), (-2,2), labels=True, label_colors='red') 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

def f(x,y): return x**2 + y**2 

g = contour_plot(f, (-2,2), (-2,2), labels=True, label_colors='red') 

sphinx_plot(g) 

 

We can add a colorbar as well:: 

 

sage: f(x, y)=x^2-y^2 

sage: contour_plot(f, (x,-3,3), (y,-3,3), colorbar=True) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

def f(x,y): return x**2 + y**2 

g = contour_plot(f, (x,-3,3), (y,-3,3), colorbar=True) 

sphinx_plot(g) 

 

:: 

 

sage: contour_plot(f, (x,-3,3), (y,-3,3), colorbar=True, colorbar_orientation='horizontal') 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

def f(x,y): return x**2 + y**2 

g = contour_plot(f, (x,-3,3), (y,-3,3), colorbar=True, colorbar_orientation='horizontal') 

sphinx_plot(g) 

 

:: 

 

sage: contour_plot(f, (x,-3,3), (y,-3,3), contours=[-2,-1,4], colorbar=True) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

def f(x,y): return x**2 + y**2 

g = contour_plot(f, (x,-3,3), (y,-3,3), contours=[-2,-1,4], 

colorbar=True) 

sphinx_plot(g) 

 

:: 

 

sage: contour_plot(f, (x,-3,3), (y,-3,3), contours=[-2,-1,4], 

....: colorbar=True, colorbar_spacing='uniform') 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

def f(x,y): return x**2 + y**2 

g = contour_plot(f, (x,-3,3), (y,-3,3), contours=[-2,-1,4], 

colorbar=True, colorbar_spacing='uniform') 

sphinx_plot(g) 

 

:: 

 

sage: contour_plot(f, (x,-3,3), (y,-3,3), contours=[0,2,3,6], 

....: colorbar=True, colorbar_format='%.3f') 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

def f(x,y): return x**2 + y**2 

g = contour_plot(f, (x,-3,3), (y,-3,3), contours=[0,2,3,6], 

colorbar=True, colorbar_format='%.3f') 

sphinx_plot(g) 

 

:: 

 

sage: contour_plot(f, (x,-3,3), (y,-3,3), labels=True, 

....: label_colors='red', contours=[0,2,3,6], 

....: colorbar=True) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

def f(x,y): return x**2 + y**2 

g = contour_plot(f, (x,-3,3), (y,-3,3), labels=True, 

label_colors='red', contours=[0,2,3,6], 

colorbar=True) 

sphinx_plot(g) 

 

:: 

 

sage: contour_plot(f, (x,-3,3), (y,-3,3), cmap='winter', 

....: contours=20, fill=False, colorbar=True) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

def f(x,y): return x**2 + y**2 

g = contour_plot(f, (x,-3,3), (y,-3,3), cmap='winter', 

contours=20, fill=False, colorbar=True) 

sphinx_plot(g) 

 

This should plot concentric circles centered at the origin:: 

 

sage: x,y = var('x,y') 

sage: contour_plot(x^2 + y^2-2,(x,-1,1), (y,-1,1)) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

g = contour_plot(x**2 + y**2-2,(x,-1,1), (y,-1,1)) 

sphinx_plot(g) 

 

 

Extra options will get passed on to show(), as long as they are valid:: 

 

sage: f(x,y) = cos(x) + sin(y) 

sage: contour_plot(f, (0,pi), (0,pi), axes=True) 

Graphics object consisting of 1 graphics primitive 

 

:: 

 

sage: contour_plot(f, (0,pi), (0,pi)).show(axes=True) # These are equivalent 

 

.. PLOT:: 

 

x,y = var('x,y') 

def f(x,y): return cos(x) + sin(y) 

g = contour_plot(f, (0,pi), (0,pi), axes=True) 

sphinx_plot(g) 

 

One can also plot over a reduced region:: 

 

sage: contour_plot(x**2 - y**2, (x,-2,2), (y,-2,2), region=x - y, plot_points=300) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

g = contour_plot(x**2 - y**2, (x,-2,2), (y,-2,2), region=x - y, 

plot_points=300) 

sphinx_plot(g) 

 

Note that with ``fill=False`` and grayscale contours, there is the 

possibility of confusion between the contours and the axes, so use 

``fill=False`` together with ``axes=True`` with caution:: 

 

sage: contour_plot(f, (-pi,pi), (-pi,pi), fill=False, axes=True) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

def f(x,y): return cos(x) + sin(y) 

g = contour_plot(f, (-pi,pi), (-pi,pi), fill=False, axes=True) 

sphinx_plot(g) 

 

TESTS: 

 

To check that :trac:`5221` is fixed, note that this has three curves, not 

two:: 

 

sage: x,y = var('x,y') 

sage: contour_plot(x - y^2, (x,-5,5), (y,-3,3), 

....: contours=[-4,-2,0], fill=False) 

Graphics object consisting of 1 graphics primitive 

""" 

from sage.plot.all import Graphics 

from sage.plot.misc import setup_for_eval_on_grid 

 

region = options.pop('region') 

ev = [f] if region is None else [f, region] 

 

F, ranges = setup_for_eval_on_grid(ev, [xrange, yrange], options['plot_points']) 

g = F[0] 

xrange, yrange = [r[:2] for r in ranges] 

 

xy_data_array = [[g(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] 

for y in xsrange(*ranges[1], include_endpoint=True)] 

 

if region is not None: 

import numpy 

 

xy_data_array = numpy.ma.asarray(xy_data_array, dtype=float) 

 

m = F[1] 

 

mask = numpy.asarray([[m(x, y) <= 0 

for x in xsrange(*ranges[0], 

include_endpoint=True)] 

for y in xsrange(*ranges[1], 

include_endpoint=True)], 

dtype=bool) 

 

xy_data_array[mask] = numpy.ma.masked 

 

g = Graphics() 

 

# Reset aspect_ratio to 'automatic' in case scale is 'semilog[xy]'. 

# Otherwise matplotlib complains. 

scale = options.get('scale', None) 

if isinstance(scale, (list, tuple)): 

scale = scale[0] 

if scale == 'semilogy' or scale == 'semilogx': 

options['aspect_ratio'] = 'automatic' 

 

g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) 

g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, options)) 

return g 

 

 

@options(plot_points=150, contours=(0,), fill=False, cmap=["blue"]) 

def implicit_plot(f, xrange, yrange, **options): 

r""" 

``implicit_plot`` takes a function of two variables, `f(x, y)` 

and plots the curve `f(x,y) = 0` over the specified 

``xrange`` and ``yrange`` as demonstrated below. 

 

``implicit_plot(f, (xmin,xmax), (ymin,ymax), ...)`` 

 

``implicit_plot(f, (x,xmin,xmax), (y,ymin,ymax), ...)`` 

 

INPUT: 

 

- ``f`` -- a function of two variables or equation in two variables 

 

- ``(xmin,xmax)`` -- 2-tuple, the range of ``x`` 

values or ``(x,xmin,xmax)`` 

 

- ``(ymin,ymax)`` -- 2-tuple, the range of ``y`` 

values or ``(y,ymin,ymax)`` 

 

The following inputs must all be passed in as named parameters: 

 

- ``plot_points`` -- integer (default: 150); number of points to plot 

in each direction of the grid 

 

- ``fill`` -- boolean (default: ``False``); if ``True``, fill the region 

`f(x, y) < 0`. 

 

- ``fillcolor`` -- string (default: ``'blue'``), the color of the region 

where `f(x,y) < 0` if ``fill = True``. Colors are defined in 

:mod:`sage.plot.colors`; try ``colors?`` to see them all. 

 

- ``linewidth`` -- integer (default: None), if a single integer all levels 

will be of the width given, otherwise the levels will be plotted with the 

widths in the order given. 

 

- ``linestyle`` -- string (default: None), the style of the line to be 

plotted, one of: ``"solid"``, ``"dashed"``, ``"dashdot"`` or 

``"dotted"``, respectively ``"-"``, ``"--"``, ``"-."``, or ``":"``. 

 

- ``color`` -- string (default: ``'blue'``), the color of the plot. Colors 

are defined in :mod:`sage.plot.colors`; try ``colors?`` to see them all. 

If ``fill = True``, then this sets only the color of the border of the 

plot. See ``fillcolor`` for setting the color of the fill region. 

 

- ``legend_label`` -- the label for this item in the legend 

 

- ``base`` -- (default: 10) the base of the logarithm if 

a logarithmic scale is set. This must be greater than 1. The base 

can be also given as a list or tuple ``(basex, basey)``. 

``basex`` sets the base of the logarithm along the horizontal 

axis and ``basey`` sets the base along the vertical axis. 

 

- ``scale`` -- (default: ``"linear"``) string. The scale of the axes. 

Possible values are ``"linear"``, ``"loglog"``, ``"semilogx"``, 

``"semilogy"``. 

 

The scale can be also be given as single argument that is a list 

or tuple ``(scale, base)`` or ``(scale, basex, basey)``. 

 

The ``"loglog"`` scale sets both the horizontal and vertical axes to 

logarithmic scale. The ``"semilogx"`` scale sets the horizontal axis 

to logarithmic scale. The ``"semilogy"`` scale sets the vertical axis 

to logarithmic scale. The ``"linear"`` scale is the default value 

when :class:`~sage.plot.graphics.Graphics` is initialized. 

 

EXAMPLES: 

 

A simple circle with a radius of 2. Note that 

since the input function is an expression, we need to explicitly 

declare the variables in 3-tuples for the range:: 

 

sage: var("x y") 

(x, y) 

sage: implicit_plot(x^2 + y^2 - 2, (x,-3,3), (y,-3,3)) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x, y =var("x y") 

g = implicit_plot(x**2 + y**2 - 2, (x,-3,3), (y,-3,3)) 

sphinx_plot(g) 

 

We can do the same thing, but using a callable function so we don't 

need to explicitly define the variables in the ranges. We also fill 

the inside:: 

 

sage: f(x,y) = x^2 + y^2 - 2 

sage: implicit_plot(f, (-3,3), (-3,3), fill=True, plot_points=500) # long time 

Graphics object consisting of 2 graphics primitives 

 

.. PLOT:: 

 

def f(x,y): return x**2 + y**2 - 2 

g = implicit_plot(f, (-3,3), (-3,3), fill=True, plot_points=500) 

sphinx_plot(g) 

 

The same circle but with a different line width:: 

 

sage: implicit_plot(f, (-3,3), (-3,3), linewidth=6) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

def f(x,y): return x**2 + y**2 - 2 

g = implicit_plot(f, (-3,3), (-3,3), linewidth=6) 

sphinx_plot(g) 

 

Again the same circle but this time with a dashdot border:: 

 

sage: implicit_plot(f, (-3,3), (-3,3), linestyle='dashdot') 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x, y =var("x y") 

def f(x,y): return x**2 + y**2 - 2 

g = implicit_plot(f, (-3,3), (-3,3), linestyle='dashdot') 

sphinx_plot(g) 

 

The same circle with different line and fill colors:: 

 

sage: implicit_plot(f, (-3,3), (-3,3), color='red', fill=True, fillcolor='green', 

....: plot_points=500) # long time 

Graphics object consisting of 2 graphics primitives 

 

.. PLOT:: 

 

def f(x,y): return x**2 + y**2 - 2 

g = implicit_plot(f, (-3,3), (-3,3), color='red', fill=True, fillcolor='green', 

plot_points=500) 

sphinx_plot(g) 

 

You can also plot an equation:: 

 

sage: var("x y") 

(x, y) 

sage: implicit_plot(x^2 + y^2 == 2, (x,-3,3), (y,-3,3)) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x, y =var("x y") 

g = implicit_plot(x**2 + y**2 == 2, (x,-3,3), (y,-3,3)) 

sphinx_plot(g) 

 

You can even change the color of the plot:: 

 

sage: implicit_plot(x^2 + y^2 == 2, (x,-3,3), (y,-3,3), color="red") 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x, y =var("x y") 

g = implicit_plot(x**2 + y**2 == 2, (x,-3,3), (y,-3,3), color="red") 

sphinx_plot(g) 

 

The color of the fill region can be changed:: 

 

sage: implicit_plot(x**2 + y**2 == 2, (x,-3,3), (y,-3,3), fill=True, fillcolor='red') 

Graphics object consisting of 2 graphics primitives 

 

.. PLOT:: 

 

x, y =var("x y") 

g = implicit_plot(x**2 + y**2 == 2, (x,-3,3), (y,-3,3), fill=True, fillcolor="red") 

sphinx_plot(g) 

 

Here is a beautiful (and long) example which also tests that all 

colors work with this:: 

 

sage: G = Graphics() 

sage: counter = 0 

sage: for col in colors.keys(): # long time 

....: G += implicit_plot(x^2 + y^2 == 1 + counter*.1, (x,-4,4),(y,-4,4), color=col) 

....: counter += 1 

sage: G # long time 

Graphics object consisting of 148 graphics primitives 

 

.. PLOT:: 

 

x, y = var("x y") 

G = Graphics() 

counter = 0 

for col in colors.keys(): 

G += implicit_plot(x**2 + y**2 == 1 + counter*.1, (x,-4,4), (y,-4,4), color=col) 

counter += 1 

sphinx_plot(G) 

 

We can define a level-`n` approximation of the boundary of the 

Mandelbrot set:: 

 

sage: def mandel(n): 

....: c = polygen(CDF, 'c') 

....: z = 0 

....: for i in range(n): 

....: z = z*z + c 

....: def f(x,y): 

....: val = z(CDF(x, y)) 

....: return val.norm() - 4 

....: return f 

 

The first-level approximation is just a circle:: 

 

sage: implicit_plot(mandel(1), (-3,3), (-3,3)) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

def mandel(n): 

c = polygen(CDF, 'c') 

z = 0 

for i in range(n): 

z = z*z + c 

def f(x,y): 

val = z(CDF(x, y)) 

return val.norm() - 4 

return f 

g = implicit_plot(mandel(1), (-3,3), (-3,3)) 

sphinx_plot(g) 

 

A third-level approximation starts to get interesting:: 

 

sage: implicit_plot(mandel(3), (-2,1), (-1.5,1.5)) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

def mandel(n): 

c = polygen(CDF, 'c') 

z = 0 

for i in range(n): 

z = z*z + c 

def f(x,y): 

val = z(CDF(x, y)) 

return val.norm() - 4 

return f 

g = implicit_plot(mandel(3), (-2,1), (-1.5,1.5)) 

sphinx_plot(g) 

 

The seventh-level approximation is a degree 64 polynomial, and 

``implicit_plot`` does a pretty good job on this part of the curve. 

(``plot_points=200`` looks even better, but it takes over a second.) 

 

:: 

 

sage: implicit_plot(mandel(7), (-0.3, 0.05), (-1.15, -0.9), plot_points=50) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

def mandel(n): 

c = polygen(CDF, 'c') 

z = 0 

for i in range(n): 

z = z*z + c 

def f(x,y): 

val = z(CDF(x, y)) 

return val.norm() - 4 

return f 

g = implicit_plot(mandel(7), (-0.3,0.05), (-1.15,-0.9), 

plot_points=50) 

sphinx_plot(g) 

 

When making a filled implicit plot using a python function rather than a 

symbolic expression the user should increase the number of plot points to 

avoid artifacts:: 

 

sage: implicit_plot(lambda x, y: x^2 + y^2 - 2, (x,-3,3), (y,-3,3), 

....: fill=True, plot_points=500) # long time 

Graphics object consisting of 2 graphics primitives 

 

.. PLOT:: 

 

x, y = var("x y") 

g = implicit_plot(lambda x, y: x**2 + y**2 - 2, (x,-3,3), (y,-3,3), 

fill=True, plot_points=500) 

sphinx_plot(g) 

 

An example of an implicit plot on 'loglog' scale:: 

 

sage: implicit_plot(x^2 + y^2 == 200, (x,1,200), (y,1,200), scale='loglog') 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x, y = var("x y") 

g = implicit_plot(x**2 + y**2 == 200, (x,1,200), (y,1,200), scale='loglog') 

sphinx_plot(g) 

 

TESTS:: 

 

sage: f(x,y) = x^2 + y^2 - 2 

sage: implicit_plot(f, (-3,3), (-3,3), fill=5) 

Traceback (most recent call last): 

... 

ValueError: fill=5 is not supported 

 

To check that :trac:`9654` is fixed:: 

 

sage: f(x,y) = x^2 + y^2 - 2 

sage: implicit_plot(f, (-3,3), (-3,3), rgbcolor=(1,0,0)) 

Graphics object consisting of 1 graphics primitive 

sage: implicit_plot(f, (-3,3), (-3,3), color='green') 

Graphics object consisting of 1 graphics primitive 

sage: implicit_plot(f, (-3,3), (-3,3), rgbcolor=(1,0,0), color='green') 

Traceback (most recent call last): 

... 

ValueError: only one of color or rgbcolor should be specified 

""" 

from sage.symbolic.expression import is_SymbolicEquation 

if is_SymbolicEquation(f): 

if f.operator() != operator.eq: 

raise ValueError("input to implicit plot must be function or equation") 

f = f.lhs() - f.rhs() 

linewidths = options.pop('linewidth', None) 

linestyles = options.pop('linestyle', None) 

 

if 'color' in options and 'rgbcolor' in options: 

raise ValueError('only one of color or rgbcolor should be specified') 

elif 'color' in options: 

options['cmap']=[options.pop('color', None)] 

elif 'rgbcolor' in options: 

options['cmap']=[rgbcolor(options.pop('rgbcolor', None))] 

 

if options['fill'] is True: 

options.pop('fill') 

options.pop('contours', None) 

incol = options.pop('fillcolor', 'blue') 

bordercol = options.pop('cmap', [None])[0] 

from sage.symbolic.expression import is_Expression 

if not is_Expression(f): 

return region_plot(lambda x, y: f(x, y) < 0, xrange, yrange, 

borderwidth=linewidths, borderstyle=linestyles, 

incol=incol, bordercol=bordercol, 

**options) 

else: 

return region_plot(f < 0, xrange, yrange, borderwidth=linewidths, 

borderstyle=linestyles, 

incol=incol, bordercol=bordercol, 

**options) 

elif options['fill'] is False: 

options.pop('fillcolor', None) 

return contour_plot(f, xrange, yrange, linewidths=linewidths, 

linestyles=linestyles, **options) 

else: 

raise ValueError("fill=%s is not supported" % options['fill']) 

 

 

@options(plot_points=100, incol='blue', outcol=None, bordercol=None, 

borderstyle=None, borderwidth=None, frame=False, axes=True, 

legend_label=None, aspect_ratio=1, alpha=1) 

def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, 

borderstyle, borderwidth, alpha, **options): 

r""" 

``region_plot`` takes a boolean function of two variables, `f(x, y)` 

and plots the region where f is True over the specified 

``xrange`` and ``yrange`` as demonstrated below. 

 

``region_plot(f, (xmin,xmax), (ymin,ymax), ...)`` 

 

INPUT: 

 

- ``f`` -- a boolean function or a list of boolean functions of 

two variables 

 

- ``(xmin,xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple 

``(x,xmin,xmax)`` 

 

- ``(ymin,ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple 

``(y,ymin,ymax)`` 

 

- ``plot_points`` -- integer (default: 100); number of points to plot 

in each direction of the grid 

 

- ``incol`` -- a color (default: ``'blue'``), the color inside the region 

 

- ``outcol`` -- a color (default: ``None``), the color of the outside 

of the region 

 

If any of these options are specified, the border will be shown as 

indicated, otherwise it is only implicit (with color ``incol``) as the 

border of the inside of the region. 

 

- ``bordercol`` -- a color (default: ``None``), the color of the border 

(``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but 

not ``bordercol``) 

 

- ``borderstyle`` -- string (default: ``'solid'``), one of ``'solid'``, 

``'dashed'``, ``'dotted'``, ``'dashdot'``, respectively ``'-'``, 

``'--'``, ``':'``, ``'-.'``. 

 

- ``borderwidth`` -- integer (default: ``None``), the width of the 

border in pixels 

 

- ``alpha`` -- (default: 1) how transparent the fill is; a number 

between 0 and 1 

 

- ``legend_label`` -- the label for this item in the legend 

 

- ``base`` - (default: 10) the base of the logarithm if 

a logarithmic scale is set. This must be greater than 1. The base 

can be also given as a list or tuple ``(basex, basey)``. 

``basex`` sets the base of the logarithm along the horizontal 

axis and ``basey`` sets the base along the vertical axis. 

 

- ``scale`` -- (default: ``"linear"``) string. The scale of the axes. 

Possible values are ``"linear"``, ``"loglog"``, ``"semilogx"``, 

``"semilogy"``. 

 

The scale can be also be given as single argument that is a list 

or tuple ``(scale, base)`` or ``(scale, basex, basey)``. 

 

The ``"loglog"`` scale sets both the horizontal and vertical axes to 

logarithmic scale. The ``"semilogx"`` scale sets the horizontal axis 

to logarithmic scale. The ``"semilogy"`` scale sets the vertical axis 

to logarithmic scale. The ``"linear"`` scale is the default value 

when :class:`~sage.plot.graphics.Graphics` is initialized. 

 

 

EXAMPLES: 

 

Here we plot a simple function of two variables:: 

 

sage: x,y = var('x,y') 

sage: region_plot(cos(x^2 + y^2) <= 0, (x,-3,3), (y,-3,3)) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

g = region_plot(cos(x**2 + y**2) <= 0, (x,-3,3), (y,-3,3)) 

sphinx_plot(g) 

 

Here we play with the colors:: 

 

sage: region_plot(x^2 + y^3 < 2, (x,-2,2), (y,-2,2), incol='lightblue', bordercol='gray') 

Graphics object consisting of 2 graphics primitives 

 

.. PLOT:: 

 

x,y = var('x,y') 

g = region_plot(x**2 + y**3 < 2, (x,-2,2), (y,-2,2), incol='lightblue', bordercol='gray') 

sphinx_plot(g) 

 

An even more complicated plot, with dashed borders:: 

 

sage: region_plot(sin(x) * sin(y) >= 1/4, (x,-10,10), (y,-10,10), 

....: incol='yellow', bordercol='black', 

....: borderstyle='dashed', plot_points=250) 

Graphics object consisting of 2 graphics primitives 

 

.. PLOT:: 

 

x,y = var('x,y') 

g = region_plot(sin(x) * sin(y) >= 1/4, (x,-10,10), (y,-10,10), 

incol='yellow', bordercol='black', 

borderstyle='dashed', plot_points=250) 

sphinx_plot(g) 

 

A disk centered at the origin:: 

 

sage: region_plot(x^2 + y^2 < 1, (x,-1,1), (y,-1,1)) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

g = region_plot(x**2 + y**2 < 1, (x,-1,1), (y,-1,1)) 

sphinx_plot(g) 

 

A plot with more than one condition (all conditions must be true for the 

statement to be true):: 

 

sage: region_plot([x^2 + y^2 < 1, x < y], (x,-2,2), (y,-2,2)) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

g = region_plot([x**2 + y**2 < 1, x < y], (x,-2,2), (y,-2,2)) 

sphinx_plot(g) 

 

Since it doesn't look very good, let's increase ``plot_points``:: 

 

sage: region_plot([x^2 + y^2 < 1, x< y], (x,-2,2), (y,-2,2), plot_points=400) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

g = region_plot([x**2 + y**2 < 1, x < y], (x,-2,2), (y,-2,2), plot_points=400) 

sphinx_plot(g) 

 

To get plots where only one condition needs to be true, use a function. 

Using lambda functions, we definitely need the extra ``plot_points``:: 

 

sage: region_plot(lambda x, y: x^2 + y^2 < 1 or x < y, (x,-2,2), (y,-2,2), plot_points=400) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x,y = var('x,y') 

g = region_plot(lambda x, y: x**2 + y**2 < 1 or x < y, (x,-2,2), (y,-2,2), plot_points=400) 

sphinx_plot(g) 

 

The first quadrant of the unit circle:: 

 

sage: region_plot([y > 0, x > 0, x^2 + y^2 < 1], (x,-1.1,1.1), (y,-1.1,1.1), plot_points=400) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x, y = var("x y") 

g = region_plot([y > 0, x > 0, x**2 + y**2 < 1], (x,-1.1,1.1), (y,-1.1,1.1), plot_points=400) 

sphinx_plot(g) 

 

Here is another plot, with a huge border:: 

 

sage: region_plot(x*(x-1)*(x+1) + y^2 < 0, (x,-3,2), (y,-3,3), 

....: incol='lightblue', bordercol='gray', borderwidth=10, 

....: plot_points=50) 

Graphics object consisting of 2 graphics primitives 

 

.. PLOT:: 

 

x, y = var("x y") 

g = region_plot(x*(x-1)*(x+1) + y**2 < 0, (x,-3,2), (y,-3,3), 

incol='lightblue', bordercol='gray', borderwidth=10, 

plot_points=50) 

sphinx_plot(g) 

 

If we want to keep only the region where x is positive:: 

 

sage: region_plot([x*(x-1)*(x+1) + y^2 < 0, x > -1], (x,-3,2), (y,-3,3), 

....: incol='lightblue', plot_points=50) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x, y =var("x y") 

g = region_plot([x*(x-1)*(x+1) + y**2 < 0, x > -1], (x,-3,2), (y,-3,3), 

incol='lightblue', plot_points=50) 

sphinx_plot(g) 

 

Here we have a cut circle:: 

 

sage: region_plot([x^2 + y^2 < 4, x > -1], (x,-2,2), (y,-2,2), 

....: incol='lightblue', bordercol='gray', plot_points=200) 

Graphics object consisting of 2 graphics primitives 

 

.. PLOT:: 

 

x, y =var("x y") 

g = region_plot([x**2 + y**2 < 4, x > -1], (x,-2,2), (y,-2,2), 

incol='lightblue', bordercol='gray', plot_points=200) 

sphinx_plot(g) 

 

The first variable range corresponds to the horizontal axis and 

the second variable range corresponds to the vertical axis:: 

 

sage: s, t = var('s, t') 

sage: region_plot(s > 0, (t,-2,2), (s,-2,2)) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

s, t = var('s, t') 

g = region_plot(s > 0, (t,-2,2), (s,-2,2)) 

sphinx_plot(g) 

 

:: 

 

sage: region_plot(s>0,(s,-2,2),(t,-2,2)) 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

s, t = var('s, t') 

g = region_plot(s > 0, (s,-2,2), (t,-2,2)) 

sphinx_plot(g) 

 

An example of a region plot in 'loglog' scale:: 

 

sage: region_plot(x^2 + y^2 < 100, (x,1,10), (y,1,10), scale='loglog') 

Graphics object consisting of 1 graphics primitive 

 

.. PLOT:: 

 

x, y = var("x y") 

g = region_plot(x**2 + y**2 < 100, (x,1,10), (y,1,10), scale='loglog') 

sphinx_plot(g) 

 

TESTS: 

 

To check that :trac:`16907` is fixed:: 

 

sage: x, y = var('x, y') 

sage: disc1 = region_plot(x^2 + y^2 < 1, (x,-1,1), (y,-1,1), alpha=0.5) 

sage: disc2 = region_plot((x-0.7)^2 + (y-0.7)^2 < 0.5, (x,-2,2), (y,-2,2), incol='red', alpha=0.5) 

sage: disc1 + disc2 

Graphics object consisting of 2 graphics primitives 

 

To check that :trac:`18286` is fixed:: 

 

sage: x, y = var('x, y') 

sage: region_plot([x == 0], (x,-1,1), (y,-1,1)) 

Graphics object consisting of 1 graphics primitive 

sage: region_plot([x^2 + y^2 == 1, x < y], (x,-1,1), (y,-1,1)) 

Graphics object consisting of 1 graphics primitive 

""" 

from sage.plot.all import Graphics 

from sage.plot.misc import setup_for_eval_on_grid 

from sage.symbolic.expression import is_Expression 

from warnings import warn 

import numpy 

 

if not isinstance(f, (list, tuple)): 

f = [f] 

 

feqs = [equify(g) for g in f if is_Expression(g) and g.operator() is operator.eq and not equify(g).is_zero()] 

f = [equify(g) for g in f if not (is_Expression(g) and g.operator() is operator.eq)] 

neqs = len(feqs) 

if neqs > 1: 

warn("There are at least 2 equations; " + 

"If the region is degenerated to points, " + 

"plotting might show nothing.") 

feqs = [sum([fn**2 for fn in feqs])] 

neqs = 1 

if neqs and not bordercol: 

bordercol = incol 

if not f: 

return implicit_plot(feqs[0], xrange, yrange, plot_points=plot_points, 

fill=False, linewidth=borderwidth, 

linestyle=borderstyle, color=bordercol, **options) 

f_all, ranges = setup_for_eval_on_grid(feqs + f, 

[xrange, yrange], 

plot_points) 

xrange, yrange = [r[:2] for r in ranges] 

 

xy_data_arrays = numpy.asarray([[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] 

for y in xsrange(*ranges[1], include_endpoint=True)] 

for func in f_all[neqs::]], dtype=float) 

xy_data_array = numpy.abs(xy_data_arrays.prod(axis=0)) 

# Now we need to set entries to negative iff all 

# functions were negative at that point. 

neg_indices = (xy_data_arrays < 0).all(axis=0) 

xy_data_array[neg_indices] = -xy_data_array[neg_indices] 

 

from matplotlib.colors import ListedColormap 

incol = rgbcolor(incol) 

if outcol: 

outcol = rgbcolor(outcol) 

cmap = ListedColormap([incol, outcol]) 

cmap.set_over(outcol, alpha=alpha) 

else: 

outcol = rgbcolor('white') 

cmap = ListedColormap([incol, outcol]) 

cmap.set_over(outcol, alpha=0) 

cmap.set_under(incol, alpha=alpha) 

 

g = Graphics() 

 

# Reset aspect_ratio to 'automatic' in case scale is 'semilog[xy]'. 

# Otherwise matplotlib complains. 

scale = options.get('scale', None) 

if isinstance(scale, (list, tuple)): 

scale = scale[0] 

if scale == 'semilogy' or scale == 'semilogx': 

options['aspect_ratio'] = 'automatic' 

 

g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) 

 

if neqs == 0: 

g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, 

dict(contours=[-1e-20, 0, 1e-20], 

cmap=cmap, 

fill=True, **options))) 

else: 

mask = numpy.asarray([[elt > 0 for elt in rows] for rows in xy_data_array], 

dtype=bool) 

xy_data_array = numpy.asarray([[f_all[0](x, y) 

for x in xsrange(*ranges[0], include_endpoint=True)] 

for y in xsrange(*ranges[1], include_endpoint=True)], 

dtype=float) 

xy_data_array[mask] = None 

if bordercol or borderstyle or borderwidth: 

cmap = [rgbcolor(bordercol)] if bordercol else ['black'] 

linestyles = [borderstyle] if borderstyle else None 

linewidths = [borderwidth] if borderwidth else None 

g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, 

dict(linestyles=linestyles, 

linewidths=linewidths, 

contours=[0], cmap=[bordercol], 

fill=False, **options))) 

 

return g 

 

 

def equify(f): 

""" 

Returns the equation rewritten as a symbolic function to give 

negative values when True, positive when False. 

 

EXAMPLES:: 

 

sage: from sage.plot.contour_plot import equify 

sage: var('x, y') 

(x, y) 

sage: equify(x^2 < 2) 

x^2 - 2 

sage: equify(x^2 > 2) 

-x^2 + 2 

sage: equify(x*y > 1) 

-x*y + 1 

sage: equify(y > 0) 

-y 

sage: f=equify(lambda x, y: x > y) 

sage: f(1, 2) 

1 

sage: f(2, 1) 

-1 

""" 

import operator 

from sage.calculus.all import symbolic_expression 

from sage.symbolic.expression import is_Expression 

if not is_Expression(f): 

return lambda x, y: -1 if f(x, y) else 1 

 

op = f.operator() 

if op is operator.gt or op is operator.ge: 

return symbolic_expression(f.rhs() - f.lhs()) 

else: 

return symbolic_expression(f.lhs() - f.rhs())