Python matplotlib.pyplot.rcParams() Examples
The following are 30
code examples of matplotlib.pyplot.rcParams().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
matplotlib.pyplot
, or try the search function
.
Example #1
Source File: style_sheets_reference.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
def plot_colored_circles(ax, prng, nb_samples=15): """Plot circle patches. NB: draws a fixed amount of samples, rather than using the length of the color cycle, because different styles may have different numbers of colors. """ for sty_dict, j in zip(plt.rcParams['axes.prop_cycle'], range(nb_samples)): ax.add_patch(plt.Circle(prng.normal(scale=3, size=2), radius=1.0, color=sty_dict['color'])) # Force the limits to be the same across the styles (because different # styles may have different numbers of available colors). ax.set_xlim([-4, 8]) ax.set_ylim([-5, 6]) ax.set_aspect('equal', adjustable='box') # to plot circles as circles return ax
Example #2
Source File: visualize.py From adversarial-policies with MIT License | 6 votes |
def _external_legend(save_path, legend_styles, legend_height): with plt.style.context([vis_styles.STYLES[style] for style in legend_styles]): width, height = plt.rcParams["figure.figsize"] height = legend_height legend_fig = plt.figure(figsize=(width, height)) handles, labels = _make_handles() legend_fig.legend( handles=handles, labels=labels, loc="lower left", mode="expand", ncol=len(handles), bbox_to_anchor=(0.0, 0.0, 1.0, 1.0), ) legend_fig.savefig(save_path) plt.close(legend_fig)
Example #3
Source File: zipf_law.py From pyhanlp with Apache License 2.0 | 6 votes |
def plot(token_counts, title='MSR语料库词频统计', ylabel='词频'): from matplotlib import pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号 fig = plt.figure( # figsize=(8, 6) ) ax = fig.add_subplot(111) token_counts = list(zip(*token_counts)) num_elements = np.arange(len(token_counts[0])) top_offset = max(token_counts[1]) + len(str(max(token_counts[1]))) ax.set_title(title) ax.set_xlabel('词语') ax.set_ylabel(ylabel) ax.xaxis.set_label_coords(1.05, 0.015) ax.set_xticks(num_elements) ax.set_xticklabels(token_counts[0], rotation=55, verticalalignment='top') ax.set_ylim([0, top_offset]) ax.set_xlim([-1, len(token_counts[0])]) rects = ax.plot(num_elements, token_counts[1], linewidth=1.5) plt.show()
Example #4
Source File: util.py From adversarial-policies with MIT License | 6 votes |
def heatmap_one_col(single_env, col, cbar, xlabel, ylabel, cmap="Blues"): width, height = plt.rcParams["figure.figsize"] if xlabel: height += 0.17 fig = plt.figure(figsize=(width, height)) cbar_width = 0.15 if cbar else 0.0 gridspec_kw = { "left": 0.2, "right": 0.98 - cbar_width, "bottom": 0.28, "top": 0.95, "wspace": 0.05, "hspace": 0.05, } single_env *= 100 / num_episodes(single_env) # convert to percentages _pretty_heatmap( single_env, col, cmap, fig, gridspec_kw, xlabel=xlabel, ylabel=ylabel, cbar_width=cbar_width ) return fig
Example #5
Source File: plotting.py From nevergrad with MIT License | 6 votes |
def split_long_title(title: str) -> str: """Splits a long title around the middle comma """ if len(title) <= 60: return title comma_indices = np.where(np.array([c for c in title]) == ",")[0] if not comma_indices.size: return title best_index = comma_indices[np.argmin(abs(comma_indices - len(title) // 2))] title = title[: (best_index + 1)] + "\n" + title[(best_index + 1):] return title # @contextlib.contextmanager # def xticks_on_top() -> tp.Iterator[None]: # values_for_top = {'xtick.bottom': False, 'xtick.labelbottom': False, # 'xtick.top': True, 'xtick.labeltop': True} # defaults = {x: plt.rcParams[x] for x in values_for_top if x in plt.rcParams} # plt.rcParams.update(values_for_top) # yield # plt.rcParams.update(defaults)
Example #6
Source File: test_frame.py From vnpy_crypto with MIT License | 6 votes |
def test_bar_colors(self): import matplotlib.pyplot as plt default_colors = self._maybe_unpack_cycler(plt.rcParams) df = DataFrame(randn(5, 5)) ax = df.plot.bar() self._check_colors(ax.patches[::5], facecolors=default_colors[:5]) tm.close() custom_colors = 'rgcby' ax = df.plot.bar(color=custom_colors) self._check_colors(ax.patches[::5], facecolors=custom_colors) tm.close() from matplotlib import cm # Test str -> colormap functionality ax = df.plot.bar(colormap='jet') rgba_colors = lmap(cm.jet, np.linspace(0, 1, 5)) self._check_colors(ax.patches[::5], facecolors=rgba_colors) tm.close() # Test colormap functionality ax = df.plot.bar(colormap=cm.jet) rgba_colors = lmap(cm.jet, np.linspace(0, 1, 5)) self._check_colors(ax.patches[::5], facecolors=rgba_colors) tm.close() ax = df.loc[:, [0]].plot.bar(color='DodgerBlue') self._check_colors([ax.patches[0]], facecolors=['DodgerBlue']) tm.close() ax = df.plot(kind='bar', color='green') self._check_colors(ax.patches[::5], facecolors=['green'] * 5) tm.close()
Example #7
Source File: example7.py From bert-as-service with MIT License | 6 votes |
def vis(embed, vis_alg='PCA', pool_alg='REDUCE_MEAN'): plt.close() fig = plt.figure() plt.rcParams['figure.figsize'] = [21, 7] for idx, ebd in enumerate(embed): ax = plt.subplot(2, 6, idx + 1) vis_x = ebd[:, 0] vis_y = ebd[:, 1] plt.scatter(vis_x, vis_y, c=subset_label, cmap=ListedColormap(["blue", "green", "yellow", "red"]), marker='.', alpha=0.7, s=2) ax.set_title('pool_layer=-%d' % (idx + 1)) plt.tight_layout() plt.subplots_adjust(bottom=0.1, right=0.95, top=0.9) cax = plt.axes([0.96, 0.1, 0.01, 0.3]) cbar = plt.colorbar(cax=cax, ticks=range(num_label)) cbar.ax.get_yaxis().set_ticks([]) for j, lab in enumerate(['ent.', 'bus.', 'sci.', 'heal.']): cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center', rotation=270) fig.suptitle('%s visualization of BERT layers using "bert-as-service" (-pool_strategy=%s)' % (vis_alg, pool_alg), fontsize=14) plt.show()
Example #8
Source File: scrapers.py From sphinx-gallery with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _anim_rst(anim, image_path, gallery_conf): from matplotlib.animation import ImageMagickWriter # output the thumbnail as the image, as it will just be copied # if it's the file thumbnail fig = anim._fig image_path = image_path.replace('.png', '.gif') fig_size = fig.get_size_inches() thumb_size = gallery_conf['thumbnail_size'] use_dpi = round( min(t_s / f_s for t_s, f_s in zip(thumb_size, fig_size))) # FFmpeg is buggy for GIFs if ImageMagickWriter.isAvailable(): writer = 'imagemagick' else: writer = None anim.save(image_path, writer=writer, dpi=use_dpi) html = anim._repr_html_() if html is None: # plt.rcParams['animation.html'] == 'none' html = anim.to_jshtml() html = indent(html, ' ') return _ANIMATION_RST.format(html)
Example #9
Source File: pylabtools.py From Computable with MIT License | 6 votes |
def print_figure(fig, fmt='png'): """Convert a figure to svg or png for inline display.""" from matplotlib import rcParams # When there's an empty figure, we shouldn't return anything, otherwise we # get big blank areas in the qt console. if not fig.axes and not fig.lines: return fc = fig.get_facecolor() ec = fig.get_edgecolor() bytes_io = BytesIO() dpi = rcParams['savefig.dpi'] if fmt == 'retina': dpi = dpi * 2 fmt = 'png' fig.canvas.print_figure(bytes_io, format=fmt, bbox_inches='tight', facecolor=fc, edgecolor=ec, dpi=dpi) data = bytes_io.getvalue() return data
Example #10
Source File: pylabtools.py From Computable with MIT License | 6 votes |
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)
Example #11
Source File: config_init.py From Computable with MIT License | 6 votes |
def mpl_style_cb(key): import sys from pandas.tools.plotting import mpl_stylesheet global style_backup val = cf.get_option(key) if 'matplotlib' not in sys.modules.keys(): if not(val): # starting up, we get reset to None return val raise Exception("matplotlib has not been imported. aborting") import matplotlib.pyplot as plt if val == 'default': style_backup = dict([(k, plt.rcParams[k]) for k in mpl_stylesheet]) plt.rcParams.update(mpl_stylesheet) elif not val: if style_backup: plt.rcParams.update(style_backup) return val
Example #12
Source File: analysis_jd_item.py From jd_analysis with GNU Lesser General Public License v3.0 | 6 votes |
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') # 分析购买后评论的时间分布
Example #13
Source File: plot.py From ms_deisotope with Apache License 2.0 | 6 votes |
def _default_color_cycle(): c = plt.rcParams['axes.prop_cycle'] colors = c.by_key().get("color") if not colors: colors = [ '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf' ] return colors
Example #14
Source File: utilities.py From HARK with Apache License 2.0 | 6 votes |
def setup_latex_env_notebook(pf, latexExists): """ This is needed for use of the latex_envs notebook extension which allows the use of environments in Markdown. Parameters ----------- pf: str (platform) output of determine_platform() """ import os from matplotlib import rc import matplotlib.pyplot as plt plt.rc('font', family='serif') plt.rc('text', usetex=latexExists) if latexExists: latex_preamble = r'\usepackage{amsmath}\usepackage{amsfonts}\usepackage[T1]{fontenc}' latexdefs_path = os.getcwd()+'/latexdefs.tex' if os.path.isfile(latexdefs_path): latex_preamble = latex_preamble+r'\input{'+latexdefs_path+r'}' else: # the required latex_envs package needs this file to exist even if it is empty from pathlib import Path Path(latexdefs_path).touch() plt.rcParams['text.latex.preamble'] = latex_preamble
Example #15
Source File: visualization.py From StainTools with MIT License | 6 votes |
def plot_row_colors(C, fig_size=6, title=None): """ Plot rows of C as colors (RGB) :param C: An array N x 3 where the rows are considered as RGB colors. :return: """ assert isinstance(C, np.ndarray), "C must be a numpy array." assert C.ndim == 2, "C must be 2D." assert C.shape[1] == 3, "C must have 3 columns." N = C.shape[0] range255 = C.max() > 1.0 # quick check to see if we have an image in range [0,1] or [0,255]. plt.rcParams['figure.figsize'] = (fig_size, fig_size) for i in range(N): if range255: plt.plot([0, 1], [N - 1 - i, N - 1 - i], c=C[i] / 255, linewidth=20) else: plt.plot([0, 1], [N - 1 - i, N - 1 - i], c=C[i], linewidth=20) if title is not None: plt.title(title) plt.axis("off") plt.axis([0, 1, -0.5, N-0.5])
Example #16
Source File: visualization.py From StainTools with MIT License | 6 votes |
def plot_image(image, show=True, fig_size=10, title=None): """ Plot an image (np.array). Caution: Rescales image to be in range [0,1]. :param image: RGB uint8 :param show: plt.show() now? :param fig_size: Size of largest dimension :param title: Image title :return: """ image = image.astype(np.float32) m, M = image.min(), image.max() if fig_size is not None: plt.rcParams['figure.figsize'] = (fig_size, fig_size) else: plt.imshow((image - m) / (M - m)) if title is not None: plt.title(title) plt.axis("off") if show: plt.show()
Example #17
Source File: pylabtools.py From Computable with MIT License | 5 votes |
def figsize(sizex, sizey): """Set the default figure size to be [sizex, sizey]. This is just an easy to remember, convenience wrapper that sets:: matplotlib.rcParams['figure.figsize'] = [sizex, sizey] """ import matplotlib matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
Example #18
Source File: pylabtools.py From Computable with MIT License | 5 votes |
def mpl_runner(safe_execfile): """Factory to return a matplotlib-enabled runner for %run. Parameters ---------- safe_execfile : function This must be a function with the same interface as the :meth:`safe_execfile` method of IPython. Returns ------- A function suitable for use as the ``runner`` argument of the %run magic function. """ def mpl_execfile(fname,*where,**kw): """matplotlib-aware wrapper around safe_execfile. Its interface is identical to that of the :func:`execfile` builtin. This is ultimately a call to execfile(), but wrapped in safeties to properly handle interactive rendering.""" import matplotlib import matplotlib.pylab as pylab #print '*** Matplotlib runner ***' # dbg # turn off rendering until end of script is_interactive = matplotlib.rcParams['interactive'] matplotlib.interactive(False) safe_execfile(fname,*where,**kw) matplotlib.interactive(is_interactive) # make rendering call now, if the user tried to do it if pylab.draw_if_interactive.called: pylab.draw() pylab.draw_if_interactive.called = False return mpl_execfile
Example #19
Source File: analysis_jd_item.py From jd_analysis with GNU Lesser General Public License v3.0 | 5 votes |
def init(self): prop = font_manager.FontProperties(fname = self.font_path) matplotlib.rcParams['font.family'] = prop.get_name() try: command = "SELECT product_color, product_size, user_level_name, user_province, reference_time, " \ "creation_time,is_mobile, user_client_show, days, user_level_name FROM {0}". \ format('item_%s' % self.product_id) result = self.sql.query(command, commit = False, cursor_type = 'dict') self.data_frame = DataFrame(result) except Exception, e: logging.exception('analysis init exception msg:%s' % e) raise CusException('analysis_init', 'analysis_init error:%s' % e)
Example #20
Source File: test_latexipy.py From latexipy with MIT License | 5 votes |
def test_font_size(self): with patch('matplotlib.rcParams.update') as mock_update, \ patch('matplotlib.pyplot.switch_backend') as mock_switch: old_params = dict(plt.rcParams) with lp.temp_params(font_size=10): called_with = mock_update.call_args[0][0] print(called_with) assert all(called_with[k] == 10 for k in lp.PARAMS if 'size' in k) mock_update.assert_called_with(old_params)
Example #21
Source File: test_latexipy.py From latexipy with MIT License | 5 votes |
def test_revert(): with patch('matplotlib.rcParams.update') as mock_update, \ patch('matplotlib.pyplot.switch_backend') as mock_switch: lp.latexify() lp.revert() mock_update.assert_called_with(dict(plt.rcParams)) mock_switch.assert_called_with(plt.get_backend())
Example #22
Source File: test_latexipy.py From latexipy with MIT License | 5 votes |
def test_raises_error_on_bad_backend(self): with patch('matplotlib.rcParams.update') as mock_update: with pytest.raises(ValueError): lp.latexify(new_backend='foo') mock_update.assert_called_once_with(lp.PARAMS)
Example #23
Source File: test_latexipy.py From latexipy with MIT License | 5 votes |
def test_params_dict(self): with patch('matplotlib.rcParams.update') as mock_update, \ patch('matplotlib.pyplot.switch_backend') as mock_switch: old_params = dict(plt.rcParams) with lp.temp_params(params_dict={'font.family': 'sans-serif'}): called_with = mock_update.call_args[0][0] assert called_with['font.family'] == 'sans-serif' mock_update.assert_called_with(old_params)
Example #24
Source File: pylabtools.py From Computable with MIT License | 5 votes |
def find_gui_and_backend(gui=None, gui_select=None): """Given a gui string return the gui and mpl backend. Parameters ---------- gui : str Can be one of ('tk','gtk','wx','qt','qt4','inline'). gui_select : str Can be one of ('tk','gtk','wx','qt','qt4','inline'). This is any gui already selected by the shell. Returns ------- A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg', 'WXAgg','Qt4Agg','module://IPython.kernel.zmq.pylab.backend_inline'). """ import matplotlib if gui and gui != 'auto': # select backend based on requested gui backend = backends[gui] else: # We need to read the backend from the original data structure, *not* # from mpl.rcParams, since a prior invocation of %matplotlib may have # overwritten that. # WARNING: this assumes matplotlib 1.1 or newer!! backend = matplotlib.rcParamsOrig['backend'] # In this case, we need to find what the appropriate gui selection call # should be for IPython, so we can activate inputhook accordingly gui = backend2gui.get(backend, None) # If we have already had a gui active, we need it and inline are the # ones allowed. if gui_select and gui != gui_select: gui = gui_select backend = backends[gui] return gui, backend
Example #25
Source File: test_frame.py From recruit with Apache License 2.0 | 5 votes |
def test_scatter_colors(self): df = DataFrame({'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}) with pytest.raises(TypeError): df.plot.scatter(x='a', y='b', c='c', color='green') default_colors = self._unpack_cycler(self.plt.rcParams) ax = df.plot.scatter(x='a', y='b', c='c') tm.assert_numpy_array_equal( ax.collections[0].get_facecolor()[0], np.array(self.colorconverter.to_rgba(default_colors[0]))) ax = df.plot.scatter(x='a', y='b', color='white') tm.assert_numpy_array_equal(ax.collections[0].get_facecolor()[0], np.array([1, 1, 1, 1], dtype=np.float64))
Example #26
Source File: plotting.py From Computable with MIT License | 5 votes |
def _get_standard_colors(num_colors=None, colormap=None, color_type='default', color=None): import matplotlib.pyplot as plt if color is None and colormap is not None: if isinstance(colormap, compat.string_types): import matplotlib.cm as cm cmap = colormap colormap = cm.get_cmap(colormap) if colormap is None: raise ValueError("Colormap {0} is not recognized".format(cmap)) colors = lmap(colormap, np.linspace(0, 1, num=num_colors)) elif color is not None: if colormap is not None: warnings.warn("'color' and 'colormap' cannot be used " "simultaneously. Using 'color'") colors = color else: if color_type == 'default': colors = plt.rcParams.get('axes.color_cycle', list('bgrcmyk')) if isinstance(colors, compat.string_types): colors = list(colors) elif color_type == 'random': import random def random_color(column): random.seed(column) return [random.random() for _ in range(3)] colors = lmap(random_color, lrange(num_colors)) else: raise NotImplementedError if len(colors) != num_colors: multiple = num_colors//len(colors) - 1 mod = num_colors % len(colors) colors += multiple * colors colors += colors[:mod] return colors
Example #27
Source File: plotting.py From Computable with MIT License | 5 votes |
def lag_plot(series, lag=1, ax=None, **kwds): """Lag plot for time series. Parameters: ----------- series: Time series lag: lag of the scatter plot, default 1 ax: Matplotlib axis object, optional kwds: Matplotlib scatter method keyword arguments, optional Returns: -------- ax: Matplotlib axis object """ import matplotlib.pyplot as plt # workaround because `c='b'` is hardcoded in matplotlibs scatter method kwds.setdefault('c', plt.rcParams['patch.facecolor']) data = series.values y1 = data[:-lag] y2 = data[lag:] if ax is None: ax = plt.gca() ax.set_xlabel("y(t)") ax.set_ylabel("y(t + %s)" % lag) ax.scatter(y1, y2, **kwds) return ax
Example #28
Source File: plotting.py From Computable with MIT License | 5 votes |
def __init__(self, data, x, y, **kwargs): MPLPlot.__init__(self, data, **kwargs) self.kwds.setdefault('c', self.plt.rcParams['patch.facecolor']) if x is None or y is None: raise ValueError( 'scatter requires and x and y column') if com.is_integer(x) and not self.data.columns.holds_integer(): x = self.data.columns[x] if com.is_integer(y) and not self.data.columns.holds_integer(): y = self.data.columns[y] self.x = x self.y = y
Example #29
Source File: test_frame.py From recruit with Apache License 2.0 | 5 votes |
def test_bar_colors(self): import matplotlib.pyplot as plt default_colors = self._unpack_cycler(plt.rcParams) df = DataFrame(randn(5, 5)) ax = df.plot.bar() self._check_colors(ax.patches[::5], facecolors=default_colors[:5]) tm.close() custom_colors = 'rgcby' ax = df.plot.bar(color=custom_colors) self._check_colors(ax.patches[::5], facecolors=custom_colors) tm.close() from matplotlib import cm # Test str -> colormap functionality ax = df.plot.bar(colormap='jet') rgba_colors = lmap(cm.jet, np.linspace(0, 1, 5)) self._check_colors(ax.patches[::5], facecolors=rgba_colors) tm.close() # Test colormap functionality ax = df.plot.bar(colormap=cm.jet) rgba_colors = lmap(cm.jet, np.linspace(0, 1, 5)) self._check_colors(ax.patches[::5], facecolors=rgba_colors) tm.close() ax = df.loc[:, [0]].plot.bar(color='DodgerBlue') self._check_colors([ax.patches[0]], facecolors=['DodgerBlue']) tm.close() ax = df.plot(kind='bar', color='green') self._check_colors(ax.patches[::5], facecolors=['green'] * 5) tm.close()
Example #30
Source File: test_frame.py From recruit with Apache License 2.0 | 5 votes |
def test_hist_colors(self): default_colors = self._unpack_cycler(self.plt.rcParams) df = DataFrame(randn(5, 5)) ax = df.plot.hist() self._check_colors(ax.patches[::10], facecolors=default_colors[:5]) tm.close() custom_colors = 'rgcby' ax = df.plot.hist(color=custom_colors) self._check_colors(ax.patches[::10], facecolors=custom_colors) tm.close() from matplotlib import cm # Test str -> colormap functionality ax = df.plot.hist(colormap='jet') rgba_colors = lmap(cm.jet, np.linspace(0, 1, 5)) self._check_colors(ax.patches[::10], facecolors=rgba_colors) tm.close() # Test colormap functionality ax = df.plot.hist(colormap=cm.jet) rgba_colors = lmap(cm.jet, np.linspace(0, 1, 5)) self._check_colors(ax.patches[::10], facecolors=rgba_colors) tm.close() ax = df.loc[:, [0]].plot.hist(color='DodgerBlue') self._check_colors([ax.patches[0]], facecolors=['DodgerBlue']) ax = df.plot(kind='hist', color='green') self._check_colors(ax.patches[::10], facecolors=['green'] * 5) tm.close()