def reset_matplotlib():
"""
Reset matplotlib to a common default.
"""
# Set all default values.
mpl.rcdefaults()
# Force agg backend.
plt.switch_backend('agg')
# These settings must be hardcoded for running the comparision tests and
# are not necessarily the default values.
mpl.rcParams['font.family'] = 'Bitstream Vera Sans'
mpl.rcParams['text.hinting'] = False
# Not available for all matplotlib versions.
try:
mpl.rcParams['text.hinting_factor'] = 8
except KeyError:
pass
import locale
locale.setlocale(locale.LC_ALL, str('en_US.UTF-8'))
# Most generic way to get the data folder path.
python类rcParams()的实例源码
def paper_plots_p4m():
import matplotlib
matplotlib.rcParams['ps.useafm'] = True
matplotlib.rcParams['pdf.use14corefonts'] = True
matplotlib.rcParams['text.usetex'] = True
im_e, fmaps_e = testplot_p4m(m=0, r=0)
im_r, fmaps_r = testplot_p4m(m=0, r=1)
im_m, fmaps_m = testplot_p4m(m=1, r=0)
plot_p4m(fmaps_e.reshape(2, 4, 7, 7), rlabels='cayley2', fontsize=10, labelpad_factor_1=0.2,
labelpad_factor_2=0.8, labelpad_factor_3=0.5, labelpad_factor_4=1.2,
figsize=(2.5, 2.5), rcolor='red', mcolor='blue')
plt.savefig('./p4m_fmap_e_mini.eps', format='eps', dpi=600)
plot_p4m(fmaps_r.reshape(2, 4, 7, 7), rlabels='cayley2', fontsize=10, labelpad_factor_1=0.2,
labelpad_factor_2=0.8, labelpad_factor_3=0.5, labelpad_factor_4=1.2,
figsize=(2.5, 2.5), rcolor='red', mcolor='blue')
plt.savefig('./p4m_fmap_r_mini.eps', format='eps', dpi=600)
plot_p4m(fmaps_m.reshape(2, 4, 7, 7), rlabels='cayley2', fontsize=10, labelpad_factor_1=0.2,
labelpad_factor_2=0.8, labelpad_factor_3=0.5, labelpad_factor_4=1.2,
figsize=(2.5, 2.5), rcolor='red', mcolor='blue')
plt.savefig('./p4m_fmap_m_mini.eps', format='eps', dpi=600)
def setup(self):
import matplotlib
def act_mpl(backend):
matplotlib.rcParams['backend'] = backend
# Save rcParams since they get modified
self._saved_rcParams = matplotlib.rcParams
self._saved_rcParamsOrig = matplotlib.rcParamsOrig
matplotlib.rcParams = dict(backend='Qt4Agg')
matplotlib.rcParamsOrig = dict(backend='Qt4Agg')
# Mock out functions
self._save_am = pt.activate_matplotlib
pt.activate_matplotlib = act_mpl
self._save_ip = pt.import_pylab
pt.import_pylab = lambda *a,**kw:None
self._save_cis = pt.configure_inline_support
pt.configure_inline_support = lambda *a,**kw:None
def latex2png(latex, filename, fontset='cm'):
latex = "$%s$" % latex
orig_fontset = rcParams['mathtext.fontset']
rcParams['mathtext.fontset'] = fontset
if os.path.exists(filename):
depth = mathtext_parser.get_depth(latex, dpi=100)
else:
try:
depth = mathtext_parser.to_png(filename, latex, dpi=100)
except:
warnings.warn("Could not render math expression %s" % latex,
Warning)
depth = 0
rcParams['mathtext.fontset'] = orig_fontset
return depth
# LaTeX to HTML translation stuff:
def plotFourListsInOnePlot(xdata, ydata1, ydata2, ydata3, ydata4, xlabel, ylabel, filename):
mpl.rcParams.update({'font.size': 20, 'lines.linewidth': 3, 'lines.markersize': 15})
# avoid type 3 (i.e. bitmap) fonts in figures
mpl.rcParams['ps.useafm'] = True
mpl.rcParams['pdf.use14corefonts'] = True
mpl.rcParams['text.usetex'] = True
plt.plot(xdata, ydata1, c='r')
plt.scatter(xdata, ydata2, marker='x', c='r', s=100)
plt.plot(xdata, ydata3, c='b')
plt.scatter(xdata, ydata4, marker='x', c='b', s=100)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.grid()
plt.tight_layout()
if filename:
plt.savefig(filename)
else:
plt.show()
def __init__(self, canvas, num, window):
FigureManagerBase.__init__(self, canvas, num)
self.window = window
self.window.withdraw()
self.set_window_title("Figure %d" % num)
self.canvas = canvas
self._num = num
_, _, w, h = canvas.figure.bbox.bounds
w, h = int(w), int(h)
self.window.minsize(int(w*3/4),int(h*3/4))
if matplotlib.rcParams['toolbar']=='classic':
self.toolbar = NavigationToolbar( canvas, self.window )
elif matplotlib.rcParams['toolbar']=='toolbar2':
self.toolbar = NavigationToolbar2TkAgg( canvas, self.window )
else:
self.toolbar = None
if self.toolbar is not None:
self.toolbar.update()
self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
self._shown = False
def notify_axes_change(fig):
'this will be called whenever the current axes is changed'
if self.toolbar != None: self.toolbar.update()
self.canvas.figure.add_axobserver(notify_axes_change)
def __init__(self, canvas, num, window):
FigureManagerBase.__init__(self, canvas, num)
self.window = window
self.window.withdraw()
self.set_window_title("Figure %d" % num)
self.canvas = canvas
self._num = num
if matplotlib.rcParams['toolbar']=='toolbar2':
self.toolbar = NavigationToolbar2TkAgg( canvas, self.window )
else:
self.toolbar = None
if self.toolbar is not None:
self.toolbar.update()
self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
self._shown = False
def notify_axes_change(fig):
'this will be called whenever the current axes is changed'
if self.toolbar != None: self.toolbar.update()
self.canvas.figure.add_axobserver(notify_axes_change)
def scoped_mpl_import():
import matplotlib
matplotlib.rcParams['backend'] = MPL_BACKEND
import matplotlib.pyplot as plt
plt.rcParams['toolbar'] = 'None' # mute matplotlib toolbar
import seaborn as sns
sns.set(style="whitegrid", color_codes=True, font_scale=1.0,
rc={'lines.linewidth': 1.0,
'backend': matplotlib.rcParams['backend']})
palette = sns.color_palette("Blues_d")
palette.reverse()
sns.set_palette(palette)
return (matplotlib, plt, sns)
def setup(self):
import matplotlib
def act_mpl(backend):
matplotlib.rcParams['backend'] = backend
# Save rcParams since they get modified
self._saved_rcParams = matplotlib.rcParams
self._saved_rcParamsOrig = matplotlib.rcParamsOrig
matplotlib.rcParams = dict(backend='Qt4Agg')
matplotlib.rcParamsOrig = dict(backend='Qt4Agg')
# Mock out functions
self._save_am = pt.activate_matplotlib
pt.activate_matplotlib = act_mpl
self._save_ip = pt.import_pylab
pt.import_pylab = lambda *a,**kw:None
self._save_cis = pt.configure_inline_support
pt.configure_inline_support = lambda *a,**kw:None
def activate_matplotlib(backend):
"""Activate the given backend and set interactive to True."""
import matplotlib
matplotlib.interactive(True)
# Matplotlib had a bug where even switch_backend could not force
# the rcParam to update. This needs to be set *before* the module
# magic of switch_backend().
matplotlib.rcParams['backend'] = backend
import matplotlib.pyplot
matplotlib.pyplot.switch_backend(backend)
# This must be imported last in the matplotlib series, after
# backend/interactivity choices have been made
import matplotlib.pyplot as plt
plt.show._needmain = False
# We need to detect at runtime whether show() is called by the user.
# For this, we wrap it into a decorator which adds a 'called' flag.
plt.draw_if_interactive = flag_calls(plt.draw_if_interactive)
def set_default_matplotlib_options():
# font options
font = {
# 'family' : 'normal',
#'weight' : 'bold',
'size' : 30
}
matplotlib.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
# matplotlib.use('cairo')
matplotlib.rc('text', usetex=True)
matplotlib.rcParams['text.usetex'] = True
plt.rc('font', **font)
plt.rc('lines', linewidth=3, markersize=10)
# matplotlib.rcParams['ps.useafm'] = True
# matplotlib.rcParams['pdf.use14corefonts'] = True
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
def plot(image, is_bgr=True, cmap=None, title='Image Viewer', disable_toolbar=True):
''' show image in matplotlib viewer. if path is given, load() first. '''
if isinstance(image, str):
image = load(str)
if disable_toolbar:
matplotlib.rcParams['toolbar'] = 'None'
# opencv image are in BGR colormap while matplotlib in RGB.
if is_bgr:
image = convert_to_rgb(image)
fig = plt.figure()
fig.canvas.set_window_title(title)
plt.imshow(image, cmap)
# hide tick values on X and Y axis.
plt.xticks([]), plt.yticks([])
plt.show()
def plot_two_images(image_1, image_2, cmap_1=None, cmap_2=None, title='Image Viewer', disable_toolbar=True):
'''
plot :image1: and :image2: in a row.
'''
if disable_toolbar:
matplotlib.rcParams['toolbar'] = 'None'
fig = plt.figure(figsize=(13, 4))
fig.canvas.set_window_title(title)
a = fig.add_subplot(1, 2, 1)
plt.imshow(image_1, cmap_1)
plt.xticks([]), plt.yticks([])
a.set_title('Before')
a = fig.add_subplot(1, 2 ,2)
plt.imshow(image_2, cmap_2)
plt.xticks([]), plt.yticks([])
a.set_title('After')
plt.show()
def plot_picks(self):
"""
Plot picks and waveform.
"""
matplotlib.rcParams["axes.labelsize"]="large"
matplotlib.rcParams["axes.linewidth"]=2.0
matplotlib.rcParams["xtick.major.size"]=8
matplotlib.rcParams["ytick.major.size"]=8
matplotlib.rcParams["ytick.minor.size"]=5
matplotlib.rcParams["xtick.labelsize"]="large"
matplotlib.rcParams["ytick.labelsize"]="large"
dt = self.stats.delta
t = np.arange(0, self.stats.npts/self.stats.sampling_rate, dt)
scnl,picks,trigger,snr = self.pick_ident()
fig = plt.figure(figsize=(10,5))
plt.plot(t, self.tr, c='gray')
for i in range(len(picks)):
plt.plot([(picks[i]-self.tr.stats.starttime), (picks[i]-self.tr.stats.starttime)], [min(self.tr),max(self.tr)], 'k--')
plt.text((picks[i]-self.tr.stats.starttime),max(self.tr)-0.3*(max(self.tr)-min(self.tr)),'%s' % (self.pol[i]),color='black')
plt.xlabel('Time (s)')
plt.show()
def __init__(self, outdir, data_key='episode_rewards', line_color='blue'):
"""
Liveplot renders a graph of either episode_rewards or episode_lengths
Args:
outdir (outdir): Monitor output file location used to populate the graph
data_key (Optional[str]): The key in the json to graph (episode_rewards or episode_lengths).
line_color (Optional[dict]): Color of the plot.
"""
#data_key can be set to 'episode_lengths'
self.outdir = outdir
self._last_data = None
self.data_key = data_key
self.line_color = line_color
#styling options
matplotlib.rcParams['toolbar'] = 'None'
plt.style.use('ggplot')
plt.xlabel("episodes")
plt.ylabel("cumulated episode rewards")
fig = plt.gcf().canvas.set_window_title('averaged_simulation_graph')
matplotlib.rcParams.update({'font.size': 15})
def plot_route_network_thumbnail(g, map_style=None):
width = 512 # pixels
height = 300 # pixels
scale = 24
dpi = mpl.rcParams["figure.dpi"]
width_m = width * scale
height_m = height * scale
median_lat, median_lon = get_median_lat_lon_of_stops(g)
dlat = util.wgs84_height(height_m)
dlon = util.wgs84_width(width_m, median_lat)
spatial_bounds = {
"lon_min": median_lon - dlon,
"lon_max": median_lon + dlon,
"lat_min": median_lat - dlat,
"lat_max": median_lat + dlat
}
fig = plt.figure(figsize=(width/dpi, height/dpi))
ax = fig.add_subplot(111)
plt.subplots_adjust(bottom=0.0, left=0.0, right=1.0, top=1.0)
return plot_route_network_from_gtfs(g, ax, spatial_bounds, map_alpha=1.0, scalebar=False, legend=False, map_style=map_style)
def set_figure_params(dpi=None, figure_formats=['png2x']):
"""Set resolution and format of figures.
Parameters
----------
dpi : int, optional
Resolution of png output in dots per inch.
figure_formats : list of strings
Only concerns the IPython environment; see
`IPython.core.display.set_matplotlib_formats` for more details. For
setting the default format for saving figures, directly set
`file_format_figs`.
"""
try:
import IPython
IPython.core.display.set_matplotlib_formats(*figure_formats)
except:
pass
from matplotlib import rcParams
global _dpi
if dpi is not None: _dpi = dpi
# need to set the following two lines as older Jupyter notebooks seem to use
# 'savefig.dpi' and more rescent ones 'figure.dpi'
rcParams['savefig.dpi'] = _dpi
rcParams['figure.dpi'] = _dpi
def figure_nobar(*args, **kwargs):
"""Make matplotlib figure with no toolbar"""
from matplotlib import rcParams, pyplot as plt
old_val = rcParams['toolbar']
try:
rcParams['toolbar'] = 'none'
fig = plt.figure(*args, **kwargs)
# remove button press catchers (for toolbar)
cbs = list(fig.canvas.callbacks.callbacks['key_press_event'].keys())
for key in cbs:
fig.canvas.callbacks.disconnect(key)
except Exception as ex:
raise ex
finally:
rcParams['toolbar'] = old_val
return fig
def setup(self):
import matplotlib
def act_mpl(backend):
matplotlib.rcParams['backend'] = backend
# Save rcParams since they get modified
self._saved_rcParams = matplotlib.rcParams
self._saved_rcParamsOrig = matplotlib.rcParamsOrig
matplotlib.rcParams = dict(backend='Qt4Agg')
matplotlib.rcParamsOrig = dict(backend='Qt4Agg')
# Mock out functions
self._save_am = pt.activate_matplotlib
pt.activate_matplotlib = act_mpl
self._save_ip = pt.import_pylab
pt.import_pylab = lambda *a,**kw:None
self._save_cis = pt.configure_inline_support
pt.configure_inline_support = lambda *a,**kw:None
def activate_matplotlib(backend):
"""Activate the given backend and set interactive to True."""
import matplotlib
matplotlib.interactive(True)
# Matplotlib had a bug where even switch_backend could not force
# the rcParam to update. This needs to be set *before* the module
# magic of switch_backend().
matplotlib.rcParams['backend'] = backend
import matplotlib.pyplot
matplotlib.pyplot.switch_backend(backend)
# This must be imported last in the matplotlib series, after
# backend/interactivity choices have been made
import matplotlib.pylab as pylab
pylab.show._needmain = False
# We need to detect at runtime whether show() is called by the user.
# For this, we wrap it into a decorator which adds a 'called' flag.
pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive)
def __init__(self, outdir, data_key='episode_rewards', line_color='blue'):
"""
Liveplot renders a graph of either episode_rewards or episode_lengths
Args:
outdir (outdir): Monitor output file location used to populate the graph
data_key (Optional[str]): The key in the json to graph (episode_rewards or episode_lengths).
line_color (Optional[dict]): Color of the plot.
"""
self.outdir = outdir
self._last_data = None
self.data_key = data_key
self.line_color = line_color
#styling options
matplotlib.rcParams['toolbar'] = 'None'
plt.style.use('ggplot')
plt.xlabel("")
plt.ylabel(data_key)
fig = plt.gcf().canvas.set_window_title('')
def writevideo(self):
#print animation.writers.list()
#matplotlib.rcParams['animation.ffmpeg_args'] = ['-report', '/tmp/ffmpeg.log']
#FFMpegWriter = animation.writers['ffmpeg']
metadata = dict(title='Github Data Projects', artist='0x0FFF',
comment='Evolution of open source data projects')
writer = FFMpegWriter(fps=30,
bitrate=8000,
metadata=metadata
)
i = 0
#self.iters = 200
with writer.saving(self.fig, "/projects/personal/writer_test.mp4", 120):
while i < self.iters:
self.update_animation(i)
writer.grab_frame()
i += 1
return
def setup(self):
import matplotlib
def act_mpl(backend):
matplotlib.rcParams['backend'] = backend
# Save rcParams since they get modified
self._saved_rcParams = matplotlib.rcParams
self._saved_rcParamsOrig = matplotlib.rcParamsOrig
matplotlib.rcParams = dict(backend='Qt4Agg')
matplotlib.rcParamsOrig = dict(backend='Qt4Agg')
# Mock out functions
self._save_am = pt.activate_matplotlib
pt.activate_matplotlib = act_mpl
self._save_ip = pt.import_pylab
pt.import_pylab = lambda *a,**kw:None
self._save_cis = pt.configure_inline_support
pt.configure_inline_support = lambda *a,**kw:None
def analysis_mobile(self):
# self.record_result('<strong style="color: black; font-size: 24px;">???????????????...</strong>')
fig_size = plt.rcParams["figure.figsize"]
plt.figure(figsize = (2.4, 2.4))
obj = self.data_frame['is_mobile']
obj = obj.value_counts()
obj = obj.rename({1: '???', 0: 'PC'})
plt.pie(x = obj.values, autopct = '%.0f%%', radius = 0.7, labels = obj.index, startangle = 180)
plt.title('?????/ PC ????')
plt.tight_layout()
filename = '%s_mobile.png' % self.product_id
plt.savefig('%s/%s' % (utils.get_save_image_path(), filename))
plt.figure(figsize = fig_size)
plt.clf()
result = utils.get_image_src(filename = filename)
self.record_result(result, type = 'image')
# ????????????
def makeDatasetsFig():
mpl.rcParams['axes.titlesize'] = 32
mpl.rcParams['axes.titleweight'] = 'bold'
mpl.rcParams['axes.facecolor'] = AXES_BG_COLOR
fig, axes = plt.subplots(2, 2)
axes = axes.flatten()
makeDishwasherFig(axes[0], save=False)
makeTidigitsFig(axes[1], save=False)
makeMsrcFig(axes[2], save=False)
makeUcrFig(axes[3], save=False)
plt.tight_layout(h_pad=2.)
saveFigWithName('datasets')
# ================================================================ Fig1
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
# Use smaller labels
rcParams['axes.labelsize'] = 'small'
rcParams['xtick.labelsize'] = 'small'
rcParams['ytick.labelsize'] = 'small'
self.axes = fig.add_axes([0.15, 0.15, 0.85, 0.85])
FigureCanvas.__init__(self, fig)
self.setParent(parent)
self.setFocusPolicy(QtCore.Qt.ClickFocus)
self.setFocus()
fig.patch.set_alpha(0)
def resizeEvent(self, event):
w = event.size().width()
h = event.size().height()
# Leave a fixed amount for the axes
padding = 7.5*FontProperties(size=rcParams['axes.labelsize']).get_size_in_points()
posx = padding/w
posy = padding/h
self.axes.set_position([posx, posy, 0.97-posx, 0.97-posy])
super(MplCanvas, self).resizeEvent(event)
def _plot_det(dets, colors, labels, title, fontsize=10, position=None):
if position is None: position = 'upper right'
# open new page for current plot
figure = pyplot.figure(figsize=(matplotlib.rcParams['figure.figsize'][0],
matplotlib.rcParams['figure.figsize'][0] * 0.975))
pyplot.grid(True)
# plot the DET curves
for i in range(len(dets)):
pyplot.plot(dets[i][0], dets[i][1], color=colors[i], label=labels[i])
# change axes accordingly
det_list = [0.0002, 0.001, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 0.7, 0.9, 0.95]
ticks = [bob.measure.ppndf(d) for d in det_list]
labels = [("%.5f" % d).rstrip('0').rstrip('.') for d in det_list]
pyplot.xticks(ticks, [l if i % 2 else "" for i,l in enumerate(labels)])
pyplot.yticks(ticks, labels)
pyplot.axis((ticks[0], ticks[-1], ticks[0], ticks[-1]))
pyplot.xlabel('FMR')
pyplot.ylabel('FNMR')
pyplot.legend(loc=position, prop = {'size':fontsize})
pyplot.title(title)
return figure
def imshow(image, ax=None, mpp=1., origin=(0, 0), ax_labels=False, **kwargs):
"""Show an image. Origin is in pixels."""
_imshow_style = dict(origin='lower', interpolation='nearest',
cmap=plt.cm.gray, aspect='equal')
_imshow_style.update(kwargs)
if not is_rgb(image, ndim=2):
try:
from pims import to_rgb
except ImportError:
raise ImportError("Imshow requires PIMS to display a non-RGB image")
image = to_rgb(image, kwargs.pop('colors', None), normed=False) / 255.
shape = image.shape[:2]
mpp = validate_tuple(mpp, ndim=2)
origin = validate_tuple(origin, ndim=2)
# extent is defined on the outer edges of the pixels
# we want the center of the topleft to intersect with the origin
extent = [(origin[1] - 0.5) * mpp[1],
(origin[1] + shape[1] - 0.5) * mpp[1],
(origin[0] - 0.5) * mpp[0],
(origin[0] + shape[0] - 0.5) * mpp[0]]
ax.imshow(image, extent=extent, **_imshow_style)
ax.set_xlim(extent[0], extent[1])
ax.set_ylim(extent[3], extent[2])
if ax_labels:
if mpp == 1.:
fmt = '{} [px]'
elif mpl.rcParams['text.usetex']:
fmt = r'{} [\textmu m]'
else:
fmt = r'{} [\xb5m]'
ax.set_xlabel(fmt.format('x'))
ax.set_ylabel(fmt.format('y'))
return ax
def generateImage(self, sourceName, fileName, image_kind):
matplotlib.rcParams['font.family'] = 'SimHei' #???????linux?????
matplotlib.rc('font', **self.FONT)
mydata = pd.read_csv(self.FILE_PATH + sourceName)
mydata.sort_index()
if image_kind == 'pie':
mydata.plot(kind='pie', subplots=True, figsize=(10,10), autopct='%1.1f%%', fontsize=20)
elif image_kind == 'bar':
mydata.plot(kind='bar', subplots=True, fontsize=10, figsize=(4,6))
else:
raise TypeError('????')
plt.savefig(self.FILE_PATH + 'images/' + fileName,dpi=100)
plt.close()