Python matplotlib.style.use() Examples
The following are 26
code examples of matplotlib.style.use().
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.style
, or try the search function
.
Example #1
Source File: main.py From amazon-price-tracker with GNU General Public License v3.0 | 6 votes |
def trackerInstance(url): item = Tracker(url) data = ItemData(url) style.use("fivethirtyeight") item.graph() if item.compare_prices() == 'below': print(f'{item.price()} < ${item.target_price}\n') comms = Communication(item.title().strip(), url, item.price(), '$' + item.target_price) comms.sendEmail() comms.sendText() data.delFile() elif item.compare_prices() == 'above': print(f'{item.price()} > ${item.target_price}\n') elif item.compare_prices() == 'out-of-stock': print(f'{item.price()} > ${item.target_price} - Item is out of stock\n')
Example #2
Source File: plot.py From hrvanalysis with GNU General Public License v3.0 | 6 votes |
def plot_distrib(nn_intervals: List[float], bin_length: int = 8): """ Function plotting histogram distribution of the NN Intervals. Useful for geometrical features. Arguments --------- nn_intervals : list list of Normal to Normal Interval. bin_length : int size of the bin for histogram in ms, by default = 8. """ max_nn_i = max(nn_intervals) min_nn_i = min(nn_intervals) style.use("seaborn-darkgrid") plt.figure(figsize=(12, 8)) plt.title("Distribution of Rr Intervals", fontsize=20) plt.xlabel("Time (s)", fontsize=15) plt.ylabel("Number of Rr Interval per bin", fontsize=15) plt.hist(nn_intervals, bins=range(min_nn_i - 10, max_nn_i + 10, bin_length), rwidth=0.8) plt.show()
Example #3
Source File: atmosphere.py From AeroSandbox with MIT License | 5 votes |
def get_density_at_altitude(altitude): # More efficient to do this using equation of state, but you can use this if you really want. P = get_pressure_at_altitude(altitude) T = get_temperature_at_altitude(altitude) rho = P / (T * R_air) return rho
Example #4
Source File: pylab.py From ipyvolume with MIT License | 5 votes |
def savefig( filename, width=None, height=None, fig=None, timeout_seconds=10, output_widget=None, headless=False, devmode=False ): """Save the figure to an image file. :param str filename: must have extension .png, .jpeg or .svg :param int width: the width of the image in pixels :param int height: the height of the image in pixels :type fig: ipyvolume.widgets.Figure or None :param fig: if None use the current figure :param float timeout_seconds: maximum time to wait for image data to return :param ipywidgets.Output output_widget: a widget to use as a context manager for capturing the data :param bool headless: if True, use headless chrome to save figure :param bool devmode: if True, attempt to get index.js from local js/dist folder """ __, ext = os.path.splitext(filename) format = ext[1:] assert format in ['png', 'jpeg', 'svg'], "image format must be png, jpeg or svg" with open(filename, "wb") as f: f.write( _screenshot_data( timeout_seconds=timeout_seconds, output_widget=output_widget, format=format, width=width, height=height, fig=fig, headless=headless, devmode=devmode, ) )
Example #5
Source File: pylab.py From ipyvolume with MIT License | 5 votes |
def screenshot( width=None, height=None, format="png", fig=None, timeout_seconds=10, output_widget=None, headless=False, devmode=False, ): """Save the figure to a PIL.Image object. :param int width: the width of the image in pixels :param int height: the height of the image in pixels :param format: format of output data (png, jpeg or svg) :type fig: ipyvolume.widgets.Figure or None :param fig: if None use the current figure :type timeout_seconds: int :param timeout_seconds: maximum time to wait for image data to return :type output_widget: ipywidgets.Output :param output_widget: a widget to use as a context manager for capturing the data :param bool headless: if True, use headless chrome to take screenshot :param bool devmode: if True, attempt to get index.js from local js/dist folder :return: PIL.Image """ assert format in ['png', 'jpeg', 'svg'], "image format must be png, jpeg or svg" data = _screenshot_data( timeout_seconds=timeout_seconds, output_widget=output_widget, format=format, width=width, height=height, fig=fig, headless=headless, devmode=devmode, ) f = StringIO(data) return PIL.Image.open(f)
Example #6
Source File: pylab.py From ipyvolume with MIT License | 5 votes |
def _screenshot_data( timeout_seconds=10, output_widget=None, format="png", width=None, height=None, fig=None, headless=False, devmode=False, ): if fig is None: fig = gcf() else: assert isinstance(fig, ipv.Figure) if headless: tempdir = tempfile.mkdtemp() tempfile_ = os.path.join(tempdir, 'headless.html') save(tempfile_, offline=True, scripts_path=tempdir, devmode=devmode) import ipyvolume.headless data = ipyvolume.headless._screenshot_data("file://" + tempfile_) if data is None: raise ValueError('Error capturing data from headless browser') else: if output_widget is None: output_widget = ipywidgets.Output() display(output_widget) # use lists to avoid globals done = [False] data = [None] def screenshot_handler(image_data): with output_widget: # print("data") # print(data) done[0] = True data[0] = image_data fig.on_screenshot(screenshot_handler) try: fig.screenshot(width=width, height=height, mime_type="image/" + format) t0 = time.time() timeout = False ipython = IPython.get_ipython() while (not done[0]) and not timeout: ipython.kernel.do_one_iteration() with output_widget: time.sleep(0.05) timeout = (time.time() - t0) > timeout_seconds with output_widget: if timeout and not done[0]: raise ValueError("timed out, no image data returned") finally: with output_widget: fig.on_screenshot(screenshot_handler, remove=True) data = data[0] data = data[data.find(",") + 1 :] return base64.b64decode(data)
Example #7
Source File: pylab.py From ipyvolume with MIT License | 5 votes |
def _axes(which=None, **values): if which: style.use({'axes': {name: values for name in which}}) else: style.use({'axes': values})
Example #8
Source File: pylab.py From ipyvolume with MIT License | 5 votes |
def animate_glyphs(*args, **kwargs): """Deprecated: please use animation_control.""" warnings.warn("Please use animation_control(...)", DeprecationWarning, stacklevel=2) animation_control(*args, **kwargs)
Example #9
Source File: pylab.py From ipyvolume with MIT License | 5 votes |
def box_on(): """Draw a box around the visible volume.""" style.use({'box': {'visible': True}})
Example #10
Source File: pylab.py From ipyvolume with MIT License | 5 votes |
def xyzlim(vmin, vmax=None): """Set limits or all axis the same, if vmax not given, use [-vmin, vmin].""" if vmax is None: vmin, vmax = -vmin, vmin xlim(vmin, vmax) ylim(vmin, vmax) zlim(vmin, vmax)
Example #11
Source File: pylab.py From ipyvolume with MIT License | 5 votes |
def background_color(color): """Set the background color.""" style.use({'background-color': color})
Example #12
Source File: pylab.py From ipyvolume with MIT License | 5 votes |
def closure(style_name=style_name): def quick_set(): style.use(style_name) attr_name = 'set_style_' + style_name attr = staticmethod(quick_set) setattr(style, attr_name, attr) getattr(style, attr_name).__doc__ = """Short for style.use(%r)""" % style_name
Example #13
Source File: styledfigure.py From ray-optics with BSD 3-Clause "New" or "Revised" License | 5 votes |
def apply_style(is_dark): """Assign a light or dark style to mpl plots.""" pth = Path(__file__).resolve().parent styles_dir = Path(pth / 'styles') if is_dark: style_path = styles_dir / 'Solarize_Dark.mplstyle' style.use(str(style_path)) else: style_path = styles_dir / 'Solarize_Light_Blue.mplstyle' style.use(str(style_path))
Example #14
Source File: plot.py From hrvanalysis with GNU General Public License v3.0 | 5 votes |
def plot_timeseries(nn_intervals: List[float], normalize: bool = True, autoscale: bool = True, y_min: float = None, y_max: float = None): """ Function plotting the NN-intervals time series. Arguments --------- nn_intervals : list list of Normal to Normal Interval. normalize : bool Set to True to plot X axis as a cumulative sum of Time. Set to False to plot X axis using x as index array 0, 1, ..., N-1. autoscale : bool Option to normalize the x-axis as a time series for comparison. Set to True by default. y_min : float Custom min value might be set for y axis. y_max : float Custom max value might be set for y axis. """ style.use("seaborn-darkgrid") plt.figure(figsize=(12, 8)) plt.title("Rr Interval time series") plt.ylabel("Rr Interval", fontsize=15) if normalize: plt.xlabel("Time (s)", fontsize=15) plt.plot(np.cumsum(nn_intervals) / 1000, nn_intervals) else: plt.xlabel("RR-interval index", fontsize=15) plt.plot(nn_intervals) if not autoscale: plt.ylim(y_min, y_max) plt.show()
Example #15
Source File: by_matplotlib.py From OnePy with MIT License | 5 votes |
def setting(self): style.use('ggplot') plt.rcParams['lines.linewidth'] = 1.4 plt.rcParams['figure.figsize'] = 6, 10
Example #16
Source File: pylab.py From ipyvolume with MIT License | 4 votes |
def save( filepath, makedirs=True, title=u'IPyVolume Widget', all_states=False, offline=False, scripts_path='js', drop_defaults=False, template_options=(("extra_script_head", ""), ("body_pre", ""), ("body_post", "")), devmode=False, offline_cors=False, ): """Save the current container to a HTML file. By default the HTML file is not standalone and requires an internet connection to fetch a few javascript libraries. Use offline=True to download these and make the HTML file work without an internet connection. :param str filepath: The file to write the HTML output to. :param bool makedirs: whether to make directories in the filename path, if they do not already exist :param str title: title for the html page :param bool all_states: if True, the state of all widgets know to the widget manager is included, else only those in widgets :param bool offline: if True, use local urls for required js/css packages and download all js/css required packages (if not already available), such that the html can be viewed with no internet connection :param str scripts_path: the folder to save required js/css packages to (relative to the filepath) :param bool drop_defaults: Whether to drop default values from the widget states :param template_options: list or dict of additional template options :param bool devmode: if True, attempt to get index.js from local js/dist folder :param bool offline_cors: if True, sets crossorigin attribute of script tags to anonymous """ ipyvolume.embed.embed_html( filepath, current.container, makedirs=makedirs, title=title, all_states=all_states, offline=offline, scripts_path=scripts_path, drop_defaults=drop_defaults, template_options=template_options, devmode=devmode, offline_cors=offline_cors, )
Example #17
Source File: faster_mix_k_means_pytorch.py From DTC with MIT License | 4 votes |
def main(): import matplotlib.pyplot as plt from matplotlib import style import pandas as pd style.use('ggplot') from sklearn.datasets import make_blobs from sklearn.metrics.cluster import normalized_mutual_info_score as nmi_score X, y = make_blobs(n_samples=500, n_features=2, centers=4, cluster_std=1, center_box=(-10.0, 10.0), shuffle=True, random_state=1) # For reproducibility cuda = torch.cuda.is_available() device = torch.device("cuda" if cuda else "cpu") # X = torch.from_numpy(X).float().to(device) y = np.array(y) l_targets = y[y>1] l_feats = X[y>1] u_feats = X[y<2] cat_feats = np.concatenate((l_feats, u_feats)) y = np.concatenate((y[y>1], y[y<2])) cat_feats = torch.from_numpy(cat_feats).to(device) u_feats = torch.from_numpy(u_feats).to(device) l_feats = torch.from_numpy(l_feats).to(device) l_targets = torch.from_numpy(l_targets).to(device) km = K_Means(k=4, init='k-means++', random_state=1, n_jobs=None, pairwise_batch_size=10) # km.fit(X) km.fit_mix(u_feats, l_feats, l_targets) # X = X.cpu() X = cat_feats.cpu() centers = km.cluster_centers_.cpu() pred = km.labels_.cpu() print('nmi', nmi_score(pred, y)) # Plotting starts here colors = 10*["g", "c", "b", "k", "r", "m"] for i in range(len(X)): x = X[i] plt.scatter(x[0], x[1], color = colors[pred[i]],s = 10) for i in range(4): plt.scatter(centers[i][0], centers[i][1], s = 130, marker = "*", color='r') plt.show()
Example #18
Source File: pylab.py From ipyvolume with MIT License | 4 votes |
def use(style): """Set the style of the current figure/visualization. :param style: matplotlib style name, or dict with values, or a sequence of these, where the last value overrides previous :return: """ def valid(value): # checks if json'able return isinstance(value, six.string_types) def translate(mplstyle): style = {} mapping = [ ['figure.facecolor', 'background-color'], ['xtick.color', 'axes.x.color'], # TODO: is this the right thing? ['xtick.color', 'axes.z.color'], # map x to z as well ['ytick.color', 'axes.y.color'], ['axes.labelcolor', 'axes.label.color'], ['text.color', 'color'], ['axes.edgecolor', 'axes.color'], ] for from_name, to_name in mapping: if from_name in mplstyle: value = mplstyle[from_name] if "color" in from_name: try: # threejs doesn't like a color like '.13', so try to convert to proper format value = float(value) * 255 value = "rgb(%d, %d, %d)" % (value, value, value) except: pass utils.nested_setitem(style, to_name, value) return style if isinstance(style, six.string_types + (dict,)): styles = [style] else: styles = style fig = gcf() totalstyle = utils.dict_deep_update({}, fig.style) for style in styles: if isinstance(style, six.string_types): if hasattr(ipyvolume.styles, style): style = getattr(ipyvolume.styles, style) else: # lets see if we can copy matplotlib's style # we assume now it's a matplotlib style, get all properties that we understand cleaned_style = { key: value for key, value in dict(matplotlib.style.library[style]).items() if valid(value) } style = translate(cleaned_style) # totalstyle.update(cleaned_style) else: # otherwise assume it's a dict pass totalstyle = utils.dict_deep_update(totalstyle, style) fig = gcf() fig.style = totalstyle
Example #19
Source File: main.py From Bitcoin-Trading-Client with GNU General Public License v2.0 | 4 votes |
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text="""The Sea of BTC trading client is a client intended to help traders interact with their exchanges. We do this by allowing you to enter your API keys into the program. We, as in Sea of BTC, never see your API information. The program may save them locally, however, to make things easier on you. Keep in mind that it is a fantastic idea to enable 'IP Whitelisting' if your exchange supports it, and only allow trading via your specific IP address. On most exchanges, even if someone was to acquire your API key, withdrawals are not possible. Some still give the option, so make sure this is turned OFF if your exchange allows it. Sea of BTC makes no promise of warranty, satisfaction, performance, or anything else. Understand that your use of this client is completely at your own risk.""", font=TITLE_FONT) label.pack(side="top", fill="x", pady=10) button1 = ttk.Button(self, text="Agree", command=lambda: controller.show_frame(dashboard)) button2 = ttk.Button(self, text="Disagree", command=quit) button1.pack() button2.pack() ### Deprecated, lost the point of needing this page leaving mostly for future reference. ##class HomePage(tk.Frame): ## def __init__(self, parent, controller): ## tk.Frame.__init__(self, parent) ## ## label = tk.Label(self, text="Sea of BTC Client", font=TITLE_FONT) ## label.pack(side="top", fill="x", pady=10) ## label = tk.Label(self, text="Choose your Exchange", font=NORM_FONT) ## label.pack(side="top", fill="x", pady=10) ## ## ## button = ttk.Button(self, text="BTC-e", ## command=lambda: controller.show_frame(BTCe_main)) ## button.pack(pady=10) ## ## button = ttk.Button(self, text="*NOT ACTIVE* Bitstamp", ## command=lambda: controller.show_frame(StartPage)) ## button.pack(pady=10) ## ## button = ttk.Button(self, text="*NOT ACTIVE* Bitfinex", ## command=lambda: controller.show_frame(StartPage)) ## button.pack(pady=10) ## ## button = ttk.Button(self, text="*NOT ACTIVE* Huobi", ## command=lambda: controller.show_frame(StartPage)) ## button.pack(pady=10)
Example #20
Source File: pylab.py From ipyvolume with MIT License | 4 votes |
def quiver( x, y, z, u, v, w, size=default_size * 10, size_selected=default_size_selected * 10, color=default_color, color_selected=default_color_selected, marker="arrow", **kwargs ): """Create a quiver plot, which is like a scatter plot but with arrows pointing in the direction given by u, v and w. :param x: {x} :param y: {y} :param z: {z} :param u: {u_dir} :param v: {v_dir} :param w: {w_dir} :param size: {size} :param size_selected: like size, but for selected glyphs :param color: {color} :param color_selected: like color, but for selected glyphs :param marker: (currently only 'arrow' would make sense) :param kwargs: extra arguments passed on to the Scatter constructor :return: :any:`Scatter` """ fig = gcf() _grow_limits(x, y, z) if 'vx' in kwargs or 'vy' in kwargs or 'vz' in kwargs: raise KeyError('Please use u, v, w instead of vx, vy, vz') s = ipv.Scatter( x=x, y=y, z=z, vx=u, vy=v, vz=w, color=color, size=size, color_selected=color_selected, size_selected=size_selected, geo=marker, **kwargs ) fig.scatters = fig.scatters + [s] return s
Example #21
Source File: pylab.py From ipyvolume with MIT License | 4 votes |
def figure( key=None, width=400, height=500, lighting=True, controls=True, controls_vr=False, controls_light=False, debug=False, **kwargs ): """Create a new figure if no key is given, or return the figure associated with key. :param key: Python object that identifies this figure :param int width: pixel width of WebGL canvas :param int height: .. height .. :param bool lighting: use lighting or not :param bool controls: show controls or not :param bool controls_vr: show controls for VR or not :param bool debug: show debug buttons or not :return: :any:`Figure` """ if key is not None and key in current.figures: current.figure = current.figures[key] current.container = current.containers[key] elif isinstance(key, ipv.Figure) and key in current.figures.values(): key_index = list(current.figures.values()).index(key) key = list(current.figures.keys())[key_index] current.figure = current.figures[key] current.container = current.containers[key] else: current.figure = ipv.Figure(width=width, height=height, **kwargs) current.container = ipywidgets.VBox() current.container.children = [current.figure] if key is None: key = uuid.uuid4().hex current.figures[key] = current.figure current.containers[key] = current.container if controls: # stereo = ipywidgets.ToggleButton(value=current.figure.stereo, description='stereo', icon='eye') # l1 = ipywidgets.jslink((current.figure, 'stereo'), (stereo, 'value')) # current.container.children += (ipywidgets.HBox([stereo, ]),) pass # stereo and fullscreen are now include in the js code (per view) if controls_vr: eye_separation = ipywidgets.FloatSlider(value=current.figure.eye_separation, min=-10, max=10, icon='eye') ipywidgets.jslink((eye_separation, 'value'), (current.figure, 'eye_separation')) current.container.children += (eye_separation,) if controls_light: globals()['controls_light']() if debug: show = ipywidgets.ToggleButtons(options=["Volume", "Back", "Front", "Coordinate"]) current.container.children += (show,) # ipywidgets.jslink((current.figure, 'show'), (show, 'value')) traitlets.link((current.figure, 'show'), (show, 'value')) return current.figure
Example #22
Source File: plot.py From hrvanalysis with GNU General Public License v3.0 | 4 votes |
def plot_poincare(nn_intervals: List[float], plot_sd_features: bool = True): """ Pointcare / Lorentz Plot of the NN Intervals Arguments --------- nn_intervals : list list of NN intervals plot_sd_features : bool Option to show or not SD1 and SD2 features on plot. By default, set to True. Notes --------- The transverse axis (T) reflects beat-to-beat variation the longitudinal axis (L) reflects the overall fluctuation """ # For Lorentz / poincaré Plot ax1 = nn_intervals[:-1] ax2 = nn_intervals[1:] # compute features for ellipse's height, width and center dict_sd1_sd2 = get_poincare_plot_features(nn_intervals) sd1 = dict_sd1_sd2["sd1"] sd2 = dict_sd1_sd2["sd2"] mean_nni = np.mean(nn_intervals) # Plot options and settings style.use("seaborn-darkgrid") fig = plt.figure(figsize=(12, 12)) ax = fig.add_subplot(111) plt.title("Poincaré / Lorentz Plot", fontsize=20) plt.xlabel('NN_n (s)', fontsize=15) plt.ylabel('NN_n+1 (s)', fontsize=15) plt.xlim(min(nn_intervals) - 10, max(nn_intervals) + 10) plt.ylim(min(nn_intervals) - 10, max(nn_intervals) + 10) # Poincaré Plot ax.scatter(ax1, ax2, c='b', s=2) if plot_sd_features: # Ellipse plot settings ells = Ellipse(xy=(mean_nni, mean_nni), width=2 * sd2 + 1, height=2 * sd1 + 1, angle=45, linewidth=2, fill=False) ax.add_patch(ells) ells = Ellipse(xy=(mean_nni, mean_nni), width=2 * sd2, height=2 * sd1, angle=45) ells.set_alpha(0.05) ells.set_facecolor("blue") ax.add_patch(ells) # Arrow plot settings sd1_arrow = ax.arrow(mean_nni, mean_nni, -sd1 * np.sqrt(2) / 2, sd1 * np.sqrt(2) / 2, linewidth=3, ec='r', fc="r", label="SD1") sd2_arrow = ax.arrow(mean_nni, mean_nni, sd2 * np.sqrt(2) / 2, sd2 * np.sqrt(2) / 2, linewidth=3, ec='g', fc="g", label="SD2") plt.legend(handles=[sd1_arrow, sd2_arrow], fontsize=12, loc="best") plt.show()
Example #23
Source File: plot.py From hrvanalysis with GNU General Public License v3.0 | 4 votes |
def plot_psd(nn_intervals: List[float], method: str = "welch", sampling_frequency: int = 7, interpolation_method: str = "linear", vlf_band: namedtuple = VlfBand(0.003, 0.04), lf_band: namedtuple = LfBand(0.04, 0.15), hf_band: namedtuple = HfBand(0.15, 0.40)): """ Function plotting the power spectral density of the NN Intervals. Arguments --------- nn_intervals : list list of Normal to Normal Interval. method : str Method used to calculate the psd. Choice are Welch's FFT (welch) or Lomb method (lomb). sampling_frequency : int frequence at which the signal is sampled. Common value range from 1 Hz to 10 Hz, by default set to 7 Hz. No need to specify if Lomb method is used. interpolation_method : str kind of interpolation as a string, by default "linear". No need to specify if lomb method is used. vlf_band : tuple Very low frequency bands for features extraction from power spectral density. lf_band : tuple Low frequency bands for features extraction from power spectral density. hf_band : tuple High frequency bands for features extraction from power spectral density. """ freq, psd = _get_freq_psd_from_nn_intervals(nn_intervals=nn_intervals, method=method, sampling_frequency=sampling_frequency, interpolation_method=interpolation_method) # Calcul of indices between desired frequency bands vlf_indexes = np.logical_and(freq >= vlf_band[0], freq < vlf_band[1]) lf_indexes = np.logical_and(freq >= lf_band[0], freq < lf_band[1]) hf_indexes = np.logical_and(freq >= hf_band[0], freq < hf_band[1]) frequency_band_index = [vlf_indexes, lf_indexes, hf_indexes] label_list = ["VLF component", "LF component", "HF component"] # Plot parameters style.use("seaborn-darkgrid") plt.figure(figsize=(12, 8)) plt.xlabel("Frequency (Hz)", fontsize=15) plt.ylabel("PSD (s2/ Hz)", fontsize=15) if method == "lomb": plt.title("Lomb's periodogram", fontsize=20) for band_index, label in zip(frequency_band_index, label_list): plt.fill_between(freq[band_index], 0, psd[band_index] / (1000 * len(psd[band_index])), label=label) plt.legend(prop={"size": 15}, loc="best") elif method == "welch": plt.title("FFT Spectrum : Welch's periodogram", fontsize=20) for band_index, label in zip(frequency_band_index, label_list): plt.fill_between(freq[band_index], 0, psd[band_index] / (1000 * len(psd[band_index])), label=label) plt.legend(prop={"size": 15}, loc="best") plt.xlim(0, hf_band[1]) else: raise ValueError("Not a valid method. Choose between 'lomb' and 'welch'") plt.show()
Example #24
Source File: plotutil.py From PlotIt with MIT License | 4 votes |
def plot_dot(xyval, color_name, xlabel, ylabel, theme, gui, dot_style, file_path): # Show plot summary print('***** Plot Summary *****') print('X,Y Value: {}'.format(xyval)) print('Color: {}'.format(color_name)) print('X-label: {}'.format(xlabel)) print('Y-label: {}'.format(ylabel)) if theme == 'dark': mplstyle.use('dark_background') else: mplstyle.use('default') try: # Check if color is hex code is_hex = re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', color_name) if not is_hex: colors = mcolors.cnames if color_name not in colors: print(color_name, ": Color not found.") color_name = 'blue' xy=xyval.split(',') l=len(xy) #Check if even number of arguments are given if (l%2==0): #Extract x-values from xyval string xval=[float(xy[i]) for i in range(0,l,2)] #Extract y-values from xyval string yval=[float(xy[i]) for i in range(1,l+1,2)] plt.scatter(xval, yval, color=color_name, marker=dot_style) plt.savefig(file_path) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(r'$ ' + xyval + ' $') if file_path != "": plt.savefig(file_path) plt.grid(True) if not gui: plt.show() else: if not os.path.exists('.temp/'): os.mkdir('.temp/') plt.savefig(".temp/generated_plot.png") else: print("Cannot plot odd Number of Coordinates") except Exception as e: print("An error occured.",e) plt.cla() plt.clf()
Example #25
Source File: plotutil.py From PlotIt with MIT License | 4 votes |
def plot_line(arrays, color_name, xlabel, ylabel, theme, gui, line_style, file_path): # Show plot summary print('***** Plot Summary *****') print('Arrays: {}'.format(arrays)) print('Color: {}'.format(color_name)) print('X-label: {}'.format(xlabel)) print('Y-label: {}'.format(ylabel)) if theme == 'dark': mplstyle.use('dark_background') else: mplstyle.use('default') try: # Check if color is hex code is_hex = re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', color_name) if not is_hex: colors = mcolors.cnames if color_name not in colors: print(color_name, ": Color not found.") color_name = 'blue' # Extract numbers from X-array xvals = list(map(float, arrays[1:arrays.find(']')].split(','))) # Extract numbers from Y-array yvals = list(map(float, arrays[arrays.find(']') + 3:len(arrays) - 1].split(','))) if len(xvals) == len(yvals): plt.plot(xvals, yvals, color=color_name, linewidth=2.0, linestyle=line_style) plt.savefig(file_path) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(r'$ ' + 'Line:' + str(xvals) +','+ str(yvals) + ' $') if file_path != "": plt.savefig(file_path) else: print("Error: You need same number of X and Y values") except Exception: raise InvalidFunctionException('Values are improper') if file_path != "": plt.savefig(file_path) plt.grid(True) if not gui: plt.show() else: if not os.path.exists('.temp/'): os.mkdir('.temp/') plt.savefig(".temp/generated_plot.png") plt.cla() plt.clf()
Example #26
Source File: plotutil.py From PlotIt with MIT License | 4 votes |
def plot(func, xpoints, color_name, xlabel, ylabel, theme, gui, line_style, file_path, discrete=False): # Show plot summary print('***** Plot Summary *****') print("Funtion: {}".format(func)) if discrete: print("Plotting funcion for points: {}".format(', '.join(map(str, xpoints)))) else: print("Starting abcissa: {}".format(xpoints[0])) print("Ending abcissa: {}".format(xpoints[-1])) if (len(xpoints) > 1): print("Stepsize: {}".format(xpoints[1] - xpoints[0])) print("Color: {}".format(color_name)) print("X-label: {}".format(xlabel)) print("Y-label: {}".format(ylabel)) print() if theme == 'dark': mplstyle.use('dark_background') else: mplstyle.use('default') xvals = xpoints yvals = create_y_values(func, xvals) try: # Check if color is hex code is_hex = re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', color_name) if not is_hex: colors = mcolors.cnames if color_name not in colors: print(color_name, ": Color not found.") color_name = 'blue' plt.plot(xvals, yvals, color=color_name, linewidth=2.0, linestyle=line_style) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(r'$ ' + func + ' $') except Exception: print("An error occured.") if file_path != "": plt.savefig(file_path) plt.grid(True) if not gui: plt.show() else: if not os.path.exists('.temp/'): os.mkdir('.temp/') plt.savefig(".temp/generated_plot.png") plt.cla() plt.clf()