Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2f3041e

Browse files
efiringNelleV
authored andcommitted
Merge pull request #7740 from vollbier/frontpage_html_plots
Beautified frontpage plots and two pylab examples
1 parent f00274f commit 2f3041e

13 files changed

+127
-59
lines changed

doc/_static/.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
contour_frontpage.png
2+
histogram_frontpage.png
3+
membrane_frontpage.png
4+
surface3d_frontpage.png
5+

doc/_static/contour_frontpage.png

-3.92 KB
Binary file not shown.

doc/_static/histogram_frontpage.png

-3.12 KB
Binary file not shown.

doc/_static/membrane_frontpage.png

-5.11 KB
Binary file not shown.

doc/_static/mpl.css

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -738,8 +738,8 @@ div.responsive_screenshots {
738738
margin: auto;
739739

740740
/* Do not go beyond 1:1 scale (and ensure a 1x4 tight layout) */
741-
max-width: 648px; /* at most 4 x 1:1 subfig width */
742-
max-height: 139px; /* at most 1 x 1:1 subfig height */
741+
max-width: 640px; /* at most 4 x 1:1 subfig width */
742+
max-height: 120px; /* at most 1 x 1:1 subfig height */
743743
}
744744

745745
/* To avoid subfigure parts outside of the responsive_screenshots */

doc/_static/surface3d_frontpage.png

-8.55 KB
Binary file not shown.

doc/make.py

Lines changed: 79 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#!/usr/bin/env python
2+
"""Wrapper script for calling Sphinx. """
23

34
from __future__ import print_function
45
import glob
@@ -7,9 +8,12 @@
78
import sys
89
import re
910
import argparse
11+
import subprocess
1012
import matplotlib
1113

14+
1215
def copy_if_out_of_date(original, derived):
16+
"""Copy file only if newer as target or if target does not exist. """
1317
if (not os.path.exists(derived) or
1418
os.stat(derived).st_mtime < os.stat(original).st_mtime):
1519
try:
@@ -22,7 +26,9 @@ def copy_if_out_of_date(original, derived):
2226
else:
2327
raise
2428

29+
2530
def check_build():
31+
"""Create target build directories if necessary. """
2632
build_dirs = ['build', 'build/doctrees', 'build/html', 'build/latex',
2733
'build/texinfo', '_static', '_templates']
2834
for d in build_dirs:
@@ -31,14 +37,58 @@ def check_build():
3137
except OSError:
3238
pass
3339

40+
3441
def doctest():
42+
"""Execute Sphinx 'doctest' target. """
3543
os.system('sphinx-build -b doctest -d build/doctrees . build/doctest')
3644

45+
3746
def linkcheck():
47+
"""Execute Sphinx 'linkcheck' target. """
3848
os.system('sphinx-build -b linkcheck -d build/doctrees . build/linkcheck')
3949

50+
51+
# For generating PNGs of the top row of index.html:
52+
FRONTPAGE_PY_PATH = "../examples/frontpage/" # python scripts location
53+
FRONTPAGE_PNG_PATH = "_static/" # png files location
54+
# png files and corresponding generation scripts:
55+
FRONTPAGE_PNGS = {"surface3d_frontpage.png": "plot_3D.py",
56+
"contour_frontpage.png": "plot_contour.py",
57+
"histogram_frontpage.png": "plot_histogram.py",
58+
"membrane_frontpage.png": "plot_membrane.py"}
59+
60+
61+
def generate_frontpage_pngs(only_if_needed=True):
62+
"""Executes the scripts for PNG generation of the top row of index.html.
63+
64+
If `only_if_needed` is `True`, then the PNG file is only generated, if it
65+
doesn't exist or if the python file is newer.
66+
67+
Note that the element `div.responsive_screenshots` in the file
68+
`_static/mpl.css` has the height and cumulative width of the used PNG files
69+
as attributes. This ensures that the magnification of those PNGs is <= 1.
70+
"""
71+
for fn_png, fn_py in FRONTPAGE_PNGS.items():
72+
pn_png = os.path.join(FRONTPAGE_PNG_PATH, fn_png) # get full paths
73+
pn_py = os.path.join(FRONTPAGE_PY_PATH, fn_py)
74+
75+
# Read file modification times:
76+
mtime_py = os.path.getmtime(pn_py)
77+
mtime_png = (os.path.getmtime(pn_png) if os.path.exists(pn_png) else
78+
mtime_py - 1) # set older time, if file doesn't exist
79+
80+
if only_if_needed and mtime_py <= mtime_png:
81+
continue # do nothing if png is newer
82+
83+
# Execute python as subprocess (preferred over os.system()):
84+
subprocess.check_call(["python", pn_py]) # raises CalledProcessError()
85+
os.rename(fn_png, pn_png) # move file to _static/ directory
86+
87+
4088
def html(buildername='html'):
89+
"""Build Sphinx 'html' target. """
4190
check_build()
91+
generate_frontpage_pngs()
4292

4393
rc = '../lib/matplotlib/mpl-data/matplotlibrc'
4494
default_rc = os.path.join(matplotlib._get_data_path(), 'matplotlibrc')
@@ -62,20 +112,24 @@ def html(buildername='html'):
62112

63113
shutil.copy('../CHANGELOG', 'build/%s/_static/CHANGELOG' % buildername)
64114

115+
65116
def htmlhelp():
117+
"""Build Sphinx 'htmlhelp' target. """
66118
html(buildername='htmlhelp')
67119
# remove scripts from index.html
68120
with open('build/htmlhelp/index.html', 'r+') as fh:
69121
content = fh.read()
70122
fh.seek(0)
71123
content = re.sub(r'<script>.*?</script>', '', content,
72-
flags=re.MULTILINE| re.DOTALL)
124+
flags=re.MULTILINE | re.DOTALL)
73125
fh.write(content)
74126
fh.truncate()
75127

128+
76129
def latex():
130+
"""Build Sphinx 'latex' target. """
77131
check_build()
78-
#figs()
132+
# figs()
79133
if sys.platform != 'win32':
80134
# LaTeX format.
81135
if os.system('sphinx-build -b latex -d build/doctrees . build/latex'):
@@ -92,9 +146,11 @@ def latex():
92146
else:
93147
print('latex build has not been tested on windows')
94148

149+
95150
def texinfo():
151+
"""Build Sphinx 'texinfo' target. """
96152
check_build()
97-
#figs()
153+
# figs()
98154
if sys.platform != 'win32':
99155
# Texinfo format.
100156
if os.system(
@@ -112,7 +168,9 @@ def texinfo():
112168
else:
113169
print('texinfo build has not been tested on windows')
114170

171+
115172
def clean():
173+
"""Remove generated files. """
116174
shutil.rmtree("build", ignore_errors=True)
117175
shutil.rmtree("examples", ignore_errors=True)
118176
for pattern in ['mpl_examples/api/*.png',
@@ -126,21 +184,27 @@ def clean():
126184
for filename in glob.glob(pattern):
127185
if os.path.exists(filename):
128186
os.remove(filename)
187+
for fn in FRONTPAGE_PNGS.keys(): # remove generated PNGs
188+
pn = os.path.join(FRONTPAGE_PNG_PATH, fn)
189+
if os.path.exists(pn):
190+
os.remove(os.path.join(pn))
191+
129192

130-
def all():
131-
#figs()
193+
def build_all():
194+
"""Build Sphinx 'html' and 'latex' target. """
195+
# figs()
132196
html()
133197
latex()
134198

135199

136200
funcd = {
137-
'html' : html,
138-
'htmlhelp' : htmlhelp,
139-
'latex' : latex,
140-
'texinfo' : texinfo,
141-
'clean' : clean,
142-
'all' : all,
143-
'doctest' : doctest,
201+
'html': html,
202+
'htmlhelp': htmlhelp,
203+
'latex': latex,
204+
'texinfo': texinfo,
205+
'clean': clean,
206+
'all': build_all,
207+
'doctest': doctest,
144208
'linkcheck': linkcheck,
145209
}
146210

@@ -167,8 +231,8 @@ def all():
167231
# This is special processing that applies on platforms that don't deal
168232
# with git symlinks -- probably only MS windows.
169233
delete = False
170-
with open(link, 'r') as content:
171-
delete = target == content.read()
234+
with open(link, 'r') as link_content:
235+
delete = target == link_content.read()
172236
if delete:
173237
symlink_warnings.append('deleted: doc/{0}'.format(link))
174238
os.unlink(link)
@@ -185,7 +249,7 @@ def all():
185249
if sys.platform == 'win32' and len(symlink_warnings) > 0:
186250
print('The following items related to symlinks will show up '
187251
'as spurious changes in your \'git status\':\n\t{0}'
188-
.format('\n\t'.join(symlink_warnings)))
252+
.format('\n\t'.join(symlink_warnings)))
189253

190254
parser = argparse.ArgumentParser(description='Build matplotlib docs')
191255
parser.add_argument("cmd", help=("Command to execute. Can be multiple. "

examples/frontpage/plot_3D.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
region = np.s_[5:50, 5:50]
2525
x, y, z = x[region], y[region], z[region]
2626

27-
fig, ax = plt.subplots(subplot_kw=dict(projection='3d'), figsize=(1.62, 1.38))
27+
fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
2828

2929
ls = LightSource(270, 45)
3030
# To use a custom hillshading mode, override the built-in shading and pass
@@ -35,4 +35,4 @@
3535
ax.set_xticks([])
3636
ax.set_yticks([])
3737
ax.set_zticks([])
38-
fig.savefig("surface3d_frontpage.png")
38+
fig.savefig("surface3d_frontpage.png", dpi=25) # results in 160x120 px image

examples/frontpage/plot_contour.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,12 @@
2323
levels = np.linspace(-2.0, 1.601, 40)
2424
norm = cm.colors.Normalize(vmax=abs(Z).max(), vmin=-abs(Z).max())
2525

26-
fig, ax = plt.subplots(figsize=(1.62, 1.38))
26+
fig, ax = plt.subplots()
2727
cset1 = ax.contourf(
2828
X, Y, Z, levels,
2929
norm=norm)
3030
ax.set_xlim(-3, 3)
3131
ax.set_ylim(-3, 3)
3232
ax.set_xticks([])
3333
ax.set_yticks([])
34-
fig.savefig("contour_frontpage.png")
34+
fig.savefig("contour_frontpage.png", dpi=25) # results in 160x120 px image

examples/frontpage/plot_histogram.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,10 @@
1313
random_state = np.random.RandomState(19680801)
1414
X = random_state.randn(10000)
1515

16-
fig, ax = plt.subplots(figsize=(1.62, 1.38))
16+
fig, ax = plt.subplots()
1717
ax.hist(X, bins=25, normed=True)
1818
x = np.linspace(-5, 5, 1000)
1919
ax.plot(x, 1 / np.sqrt(2*np.pi) * np.exp(-(x**2)/2), linewidth=4)
2020
ax.set_xticks([])
2121
ax.set_yticks([])
22-
fig.savefig("histogram_frontpage.png")
22+
fig.savefig("histogram_frontpage.png", dpi=25) # results in 160x120 px image

examples/frontpage/plot_membrane.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,10 @@
1616
x = np.fromfile(datafile, np.float32)
1717
# 0.0005 is the sample interval
1818

19-
fig, ax = plt.subplots(figsize=(1.62, 1.38))
19+
fig, ax = plt.subplots()
2020
ax.plot(x, linewidth=4)
2121
ax.set_xlim(5000, 6000)
2222
ax.set_ylim(-0.6, 0.1)
2323
ax.set_xticks([])
2424
ax.set_yticks([])
25-
fig.savefig("membrane_frontpage.png")
25+
fig.savefig("membrane_frontpage.png", dpi=25) # results in 160x120 px image

examples/pie_and_polar_charts/pie_demo_features.py

Lines changed: 29 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -16,43 +16,40 @@
1616
rotated counter-clockwise by 90 degrees, and the frog slice starts on the
1717
positive y-axis.
1818
"""
19+
import numpy as np
1920
import matplotlib.pyplot as plt
2021

21-
# The slices will be ordered and plotted counter-clockwise.
22+
# Pie chart, where the slices will be ordered and plotted counter-clockwise:
2223
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
2324
sizes = [15, 30, 45, 10]
2425
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
2526

26-
plt.pie(sizes, explode=explode, labels=labels,
27-
autopct='%1.1f%%', shadow=True, startangle=90)
28-
# Set aspect ratio to be equal so that pie is drawn as a circle.
29-
plt.axis('equal')
30-
31-
fig = plt.figure()
32-
ax = fig.gca()
33-
import numpy as np
34-
35-
ax.pie(np.random.random(4), explode=explode, labels=labels,
36-
autopct='%1.1f%%', shadow=True, startangle=90,
37-
radius=0.25, center=(0, 0), frame=True)
38-
ax.pie(np.random.random(4), explode=explode, labels=labels,
39-
autopct='%1.1f%%', shadow=True, startangle=90,
40-
radius=0.25, center=(1, 1), frame=True)
41-
ax.pie(np.random.random(4), explode=explode, labels=labels,
42-
autopct='%1.1f%%', shadow=True, startangle=90,
43-
radius=0.25, center=(0, 1), frame=True)
44-
ax.pie(np.random.random(4), explode=explode, labels=labels,
45-
autopct='%1.1f%%', shadow=True, startangle=90,
46-
radius=0.25, center=(1, 0), frame=True)
47-
48-
ax.set_xticks([0, 1])
49-
ax.set_yticks([0, 1])
50-
ax.set_xticklabels(["Sunny", "Cloudy"])
51-
ax.set_yticklabels(["Dry", "Rainy"])
52-
ax.set_xlim((-0.5, 1.5))
53-
ax.set_ylim((-0.5, 1.5))
54-
55-
# Set aspect ratio to be equal so that pie is drawn as a circle.
56-
ax.set_aspect('equal')
27+
fg1, ax1 = plt.subplots()
28+
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
29+
shadow=True, startangle=90)
30+
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
31+
32+
33+
# Plot four Pie charts in a 2x2 grid:
34+
pie_data = [np.roll(sizes, i) for i in range(4)] # generate some data
35+
pie_centerpos = [(0, 0), (0, 1), (1, 0), (1, 1)] # the grid positions
36+
37+
fg2, ax2 = plt.subplots()
38+
for data, cpos in zip(pie_data, pie_centerpos):
39+
_, txts = ax2.pie(data, explode=explode, shadow=True, startangle=90,
40+
radius=0.35, center=cpos, frame=True, labeldistance=.7)
41+
# Make texts include number and labels:
42+
for t, l, d in zip(txts, labels, data):
43+
t.set_text("%s\n %.1f%%" % (l, d))
44+
t.set_horizontalalignment("center")
45+
t.set_fontsize(8)
46+
47+
ax2.set_xticks([0, 1])
48+
ax2.set_yticks([0, 1])
49+
ax2.set_xticklabels(["Sunny", "Cloudy"])
50+
ax2.set_yticklabels(["Dry", "Rainy"])
51+
ax2.set_xlim((-0.5, 1.5))
52+
ax2.set_ylim((-0.5, 1.5))
53+
ax2.set_aspect('equal') # Equal aspect ratio ensures that the pie is a circle.
5754

5855
plt.show()

examples/pylab_examples/polar_demo.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,14 @@
55
import matplotlib.pyplot as plt
66

77

8-
r = np.arange(0, 3.0, 0.01)
8+
r = np.arange(0, 2, 0.01)
99
theta = 2 * np.pi * r
1010

1111
ax = plt.subplot(111, projection='polar')
1212
ax.plot(theta, r)
13-
ax.set_rmax(2.0)
13+
ax.set_rmax(2)
14+
ax.set_rticks([0.5, 1, 1.5, 2]) # less radial ticks
15+
ax.set_rlabel_position(-22.5) # get radial labels away from plotted line
1416
ax.grid(True)
1517

1618
ax.set_title("A line plot on a polar axis", va='bottom')

0 commit comments

Comments
 (0)