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

Skip to content

Commit 643c74b

Browse files
committed
Add easy style sheet selection.
1 parent 9290f57 commit 643c74b

File tree

9 files changed

+311
-1
lines changed

9 files changed

+311
-1
lines changed

doc/conf.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@
2828
extensions = ['matplotlib.sphinxext.mathmpl', 'sphinxext.math_symbol_table',
2929
'sphinx.ext.autodoc', 'matplotlib.sphinxext.only_directives',
3030
'sphinx.ext.doctest', 'sphinx.ext.autosummary',
31-
'matplotlib.sphinxext.plot_directive', 'sphinx.ext.inheritance_diagram',
31+
'matplotlib.sphinxext.plot_directive',
32+
'sphinx.ext.inheritance_diagram',
3233
'sphinxext.gen_gallery', 'sphinxext.gen_rst',
3334
'matplotlib.sphinxext.ipython_console_highlighting',
3435
'sphinxext.github',
@@ -117,6 +118,7 @@
117118
('text_labels_and_annotations', 'Text, labels, and annotations'),
118119
('ticks_and_spines', 'Ticks and spines'),
119120
('subplots_axes_and_figures', 'Subplots, axes, and figures'),
121+
('style_sheets', 'Style sheets'),
120122
('specialty_plots', 'Specialty plots'),
121123
('showcase', 'Showcase'),
122124
('api', 'API'),
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""
2+
This example demonstrates the "dark_background" style, which uses white for
3+
elements that are typically black (text, borders, etc). Note, however, that not
4+
all plot elements default to colors defined by an rc parameter.
5+
6+
"""
7+
import numpy as np
8+
import matplotlib.pyplot as plt
9+
10+
from matplotlib import style
11+
style.use('dark_background')
12+
13+
14+
L = 6
15+
x = np.linspace(0, L)
16+
ncolors = len(plt.rcParams['axes.color_cycle'])
17+
shift = np.linspace(0, L, ncolors, endpoint=False)
18+
for s in shift:
19+
plt.plot(x, np.sin(x + s), 'o-')
20+
plt.xlabel('x-axis')
21+
plt.ylabel('y-axis')
22+
plt.title('title')
23+
24+
plt.show()

examples/style_sheets/plot_ggplot.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""
2+
This example demonstrates the "ggplot" style, which adjusts the style to
3+
emulate ggplot_ (a popular plotting package for R_).
4+
5+
These settings were shamelessly stolen from [1]_ (with permission).
6+
7+
.. [1] http://www.huyng.com/posts/sane-color-scheme-for-matplotlib/
8+
9+
.. _ggplot: http://had.co.nz/ggplot/
10+
.. _R: http://www.r-project.org/
11+
12+
"""
13+
import numpy as np
14+
import matplotlib.pyplot as plt
15+
from matplotlib import style
16+
17+
style.use('ggplot')
18+
19+
fig, axes = plt.subplots(ncols=2, nrows=2)
20+
ax1, ax2, ax3, ax4 = axes.ravel()
21+
22+
# scatter plot (Note: `plt.scatter` doesn't use default colors)
23+
x, y = np.random.normal(size=(2, 200))
24+
ax1.plot(x, y, 'o')
25+
26+
# sinusoidal lines with colors from default color cycle
27+
L = 2*np.pi
28+
x = np.linspace(0, L)
29+
ncolors = len(plt.rcParams['axes.color_cycle'])
30+
shift = np.linspace(0, L, ncolors, endpoint=False)
31+
for s in shift:
32+
ax2.plot(x, np.sin(x + s), '-')
33+
ax2.margins(0)
34+
35+
# bar graphs
36+
x = np.arange(5)
37+
y1, y2 = np.random.randint(1, 25, size=(2, 5))
38+
width = 0.25
39+
ax3.bar(x, y1, width)
40+
ax3.bar(x+width, y2, width, color=plt.rcParams['axes.color_cycle'][2])
41+
ax3.set_xticks(x+width)
42+
ax3.set_xticklabels(['a', 'b', 'c', 'd', 'e'])
43+
44+
# circles with colors from default color cycle
45+
for i, color in enumerate(plt.rcParams['axes.color_cycle']):
46+
xy = np.random.normal(size=2)
47+
ax4.add_patch(plt.Circle(xy, radius=0.3, color=color))
48+
ax4.axis('equal')
49+
ax4.margins(0)
50+
51+
plt.show()
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""
2+
This example demonstrates the "grayscale" style sheet, which changes all colors
3+
that are defined as rc parameters to grayscale. Note, however, that not all
4+
plot elements default to colors defined by an rc parameter.
5+
6+
"""
7+
import numpy as np
8+
import matplotlib.pyplot as plt
9+
10+
from matplotlib import style
11+
12+
13+
def color_cycle_example(ax):
14+
L = 6
15+
x = np.linspace(0, L)
16+
ncolors = len(plt.rcParams['axes.color_cycle'])
17+
shift = np.linspace(0, L, ncolors, endpoint=False)
18+
for s in shift:
19+
ax.plot(x, np.sin(x + s), 'o-')
20+
21+
def image_and_patch_example(ax):
22+
ax.imshow(np.random.random(size=(20, 20)), interpolation='none')
23+
c = plt.Circle((5, 5), radius=5, label='patch')
24+
ax.add_patch(c)
25+
26+
27+
style.use('grayscale')
28+
29+
fig, (ax1, ax2) = plt.subplots(ncols=2)
30+
31+
color_cycle_example(ax1)
32+
image_and_patch_example(ax2)
33+
34+
plt.show()

lib/matplotlib/style/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
from core import *
2+

lib/matplotlib/style/core.py

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
"""
2+
Core functions and attributes for the matplotlib style library:
3+
4+
``use``
5+
Select style sheet to override the current matplotlib settings.
6+
``available``
7+
List available style sheets.
8+
``library``
9+
A dictionary of style names and matplotlib settings.
10+
"""
11+
import os
12+
import re
13+
14+
import numpy as np
15+
import matplotlib.pyplot as plt
16+
import matplotlib as mpl
17+
18+
19+
__all__ = ['use', 'available', 'library']
20+
21+
22+
_here = os.path.abspath(os.path.dirname(__file__))
23+
BASE_LIBRARY_PATH = os.path.join(_here, 'stylelib')
24+
# Users may want multiple library paths, so store a list of paths.
25+
USER_LIBRARY_PATHS = [os.path.join('~', '.matplotlib', 'stylelib')]
26+
STYLE_FILE_PATTERN = re.compile('([A-Za-z._-]+).mplrc$')
27+
28+
29+
def use(name):
30+
"""Use matplotlib rc parameters from a pre-defined name or from a file.
31+
32+
Parameters
33+
----------
34+
name : str or list of str
35+
Name of style. For list of available styles see `style.available`.
36+
If given a list, each style is applied from first to last in the list.
37+
"""
38+
if np.isscalar(name):
39+
name = [name]
40+
for s in name:
41+
plt.rcParams.update(library[s])
42+
43+
44+
def load_base_library():
45+
"""Load style library defined in this package."""
46+
library = dict()
47+
library.update(read_style_directory(BASE_LIBRARY_PATH))
48+
return library
49+
50+
51+
def iter_user_libraries():
52+
for stylelib_path in USER_LIBRARY_PATHS:
53+
stylelib_path = os.path.expanduser(stylelib_path)
54+
if os.path.exists(stylelib_path) and os.path.isdir(stylelib_path):
55+
yield stylelib_path
56+
57+
58+
def update_user_library(library):
59+
"""Update style library with user-defined rc files"""
60+
for stylelib_path in iter_user_libraries():
61+
styles = read_style_directory(stylelib_path)
62+
update_nested_dict(library, styles)
63+
return library
64+
65+
66+
def iter_style_files(style_dir):
67+
"""Yield file path and name of styles in the given directory."""
68+
for path in os.listdir(style_dir):
69+
filename = os.path.basename(path)
70+
match = STYLE_FILE_PATTERN.match(filename)
71+
if match:
72+
path = os.path.abspath(os.path.join(style_dir, path))
73+
yield path, match.groups()[0]
74+
75+
76+
def read_style_directory(style_dir):
77+
"""Return dictionary of styles defined in `style_dir`."""
78+
styles = dict()
79+
for path, name in iter_style_files(style_dir):
80+
styles[name] = mpl.rc_params_from_file(path)
81+
return styles
82+
83+
84+
def update_nested_dict(main_dict, new_dict):
85+
"""Update nested dict (only level of nesting) with new values.
86+
87+
Unlike dict.update, this assumes that the values of the parent dict are
88+
dicts (or dict-like), so you shouldn't replace the nested dict if it
89+
already exists. Instead you should update the sub-dict.
90+
"""
91+
# update named styles specified by user
92+
for name, rc_dict in new_dict.iteritems():
93+
if name in main_dict:
94+
# FIXME: This is currently broken because rc_params_from_file fills
95+
# in all settings so the update overwrites all values.
96+
main_dict[name].update(rc_dict)
97+
else:
98+
main_dict[name] = rc_dict
99+
return main_dict
100+
101+
102+
# Load style library
103+
# ==================
104+
_base_library = load_base_library()
105+
library = update_user_library(_base_library)
106+
available = library.keys()
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Set black background default line colors to white.
2+
3+
lines.color: white
4+
patch.edgecolor: white
5+
6+
text.color: white
7+
8+
axes.facecolor: black
9+
axes.edgecolor: white
10+
axes.labelcolor: white
11+
axes.color_cycle: 8dd3c7, feffb3, bfbbd9, fa8174, 81b1d2, fdb462, b3de69, bc82bd, ccebc4, ffed6f
12+
13+
xtick.color: white
14+
ytick.color: white
15+
16+
grid.color: white
17+
18+
figure.facecolor: black
19+
figure.edgecolor: black
20+
21+
savefig.facecolor: black
22+
savefig.edgecolor: black
23+
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# from http://www.huyng.com/posts/sane-color-scheme-for-matplotlib/
2+
3+
patch.linewidth: 0.5
4+
patch.facecolor: 348ABD # blue
5+
patch.edgecolor: EEEEEE
6+
patch.antialiased: True
7+
8+
font.size: 10.0
9+
10+
axes.facecolor: E5E5E5
11+
axes.edgecolor: white
12+
axes.linewidth: 1
13+
axes.grid: True
14+
axes.titlesize: x-large
15+
axes.labelsize: large
16+
axes.labelcolor: 555555
17+
axes.axisbelow: True # grid/ticks are below elements (eg lines, text)
18+
19+
axes.color_cycle: E24A33, 348ABD, 988ED5, 777777, FBC15E, 8EBA42, FFB5B8
20+
# E24A33 : red
21+
# 348ABD : blue
22+
# 988ED5 : purple
23+
# 777777 : gray
24+
# FBC15E : yellow
25+
# 8EBA42 : green
26+
# FFB5B8 : pink
27+
28+
xtick.color: 555555
29+
xtick.direction: out
30+
31+
ytick.color: 555555
32+
ytick.direction: out
33+
34+
grid.color: white
35+
grid.linestyle: - # solid line
36+
37+
figure.facecolor: white
38+
figure.edgecolor: 0.50
39+
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Set all colors to grayscale
2+
# Note: strings of float values are interpreted by matplotlib as gray values.
3+
4+
5+
lines.color: black
6+
patch.facecolor: gray
7+
patch.edgecolor: black
8+
9+
text.color: black
10+
11+
axes.facecolor: white
12+
axes.edgecolor: black
13+
axes.labelcolor: black
14+
# black to light gray
15+
axes.color_cycle: 0.00, 0.40, 0.60, 0.70
16+
17+
xtick.color: black
18+
ytick.color: black
19+
20+
grid.color: black
21+
22+
figure.facecolor: 0.75
23+
figure.edgecolor: white
24+
25+
image.cmap: gray
26+
27+
savefig.facecolor: white
28+
savefig.edgecolor: white
29+

0 commit comments

Comments
 (0)