Python matplotlib.pyplot.margins() Examples

The following are code examples for showing how to use matplotlib.pyplot.margins(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: razzy-spinner   Author: rafasashi   File: util.py    GNU General Public License v3.0 9 votes vote down vote up
def _show_plot(x_values, y_values, x_labels=None, y_labels=None):
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError('The plot function requires matplotlib to be installed.'
                         'See http://matplotlib.org/')

    plt.locator_params(axis='y', nbins=3)
    axes = plt.axes()
    axes.yaxis.grid()
    plt.plot(x_values, y_values, 'ro', color='red')
    plt.ylim(ymin=-1.2, ymax=1.2)
    plt.tight_layout(pad=5)
    if x_labels:
        plt.xticks(x_values, x_labels, rotation='vertical')
    if y_labels:
        plt.yticks([-1, 0, 1], y_labels, rotation='horizontal')
    # Pad margins so that markers are not clipped by the axes
    plt.margins(0.2)
    plt.show()

#////////////////////////////////////////////////////////////
#{ Parsing and conversion functions
#//////////////////////////////////////////////////////////// 
Example 2
Project: OpenBottle   Author: xiaozhuchacha   File: util.py    MIT License 6 votes vote down vote up
def _show_plot(x_values, y_values, x_labels=None, y_labels=None):
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError('The plot function requires matplotlib to be installed.'
                         'See http://matplotlib.org/')

    plt.locator_params(axis='y', nbins=3)
    axes = plt.axes()
    axes.yaxis.grid()
    plt.plot(x_values, y_values, 'ro', color='red')
    plt.ylim(ymin=-1.2, ymax=1.2)
    plt.tight_layout(pad=5)
    if x_labels:
        plt.xticks(x_values, x_labels, rotation='vertical')
    if y_labels:
        plt.yticks([-1, 0, 1], y_labels, rotation='horizontal')
    # Pad margins so that markers are not clipped by the axes
    plt.margins(0.2)
    plt.show()

#////////////////////////////////////////////////////////////
#{ Parsing and conversion functions
#//////////////////////////////////////////////////////////// 
Example 3
Project: OpenBottle   Author: xiaozhuchacha   File: util.py    MIT License 6 votes vote down vote up
def _show_plot(x_values, y_values, x_labels=None, y_labels=None):
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError('The plot function requires matplotlib to be installed.'
                         'See http://matplotlib.org/')

    plt.locator_params(axis='y', nbins=3)
    axes = plt.axes()
    axes.yaxis.grid()
    plt.plot(x_values, y_values, 'ro', color='red')
    plt.ylim(ymin=-1.2, ymax=1.2)
    plt.tight_layout(pad=5)
    if x_labels:
        plt.xticks(x_values, x_labels, rotation='vertical')
    if y_labels:
        plt.yticks([-1, 0, 1], y_labels, rotation='horizontal')
    # Pad margins so that markers are not clipped by the axes
    plt.margins(0.2)
    plt.show()

#////////////////////////////////////////////////////////////
#{ Parsing and conversion functions
#//////////////////////////////////////////////////////////// 
Example 4
Project: Health-Checker   Author: KriAga   File: util.py    MIT License 6 votes vote down vote up
def _show_plot(x_values, y_values, x_labels=None, y_labels=None):
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError('The plot function requires matplotlib to be installed.'
                         'See http://matplotlib.org/')

    plt.locator_params(axis='y', nbins=3)
    axes = plt.axes()
    axes.yaxis.grid()
    plt.plot(x_values, y_values, 'ro', color='red')
    plt.ylim(ymin=-1.2, ymax=1.2)
    plt.tight_layout(pad=5)
    if x_labels:
        plt.xticks(x_values, x_labels, rotation='vertical')
    if y_labels:
        plt.yticks([-1, 0, 1], y_labels, rotation='horizontal')
    # Pad margins so that markers are not clipped by the axes
    plt.margins(0.2)
    plt.show()

#////////////////////////////////////////////////////////////
#{ Parsing and conversion functions
#//////////////////////////////////////////////////////////// 
Example 5
Project: atlantisbot   Author: johnvictorfs   File: tools.py    MIT License 6 votes vote down vote up
def plot_table(table_name: str, image_name: str, safe: bool = True):
    # https://stackoverflow.com/questions/35634238/how-to-save-a-pandas-dataframe-table-as-a-png
    df = pd.read_sql(table_name, engine)
    if safe:
        if table_name == 'amigosecreto':
            df = df.drop(['id', 'giving_to_user_id', 'receiving'], axis=1)
    fig, ax = plt.subplots(figsize=(12, 2))  # set size frame
    ax.xaxis.set_visible(False)  # hide the x axis
    ax.yaxis.set_visible(False)  # hide the y axis
    ax.set_frame_on(False)  # no visible frame
    table(ax, df, loc='upper right', colWidths=[0.17] * len(df.columns))

    # https://stackoverflow.com/questions/11837979/removing-white-space-around-a-saved-image-in-matplotlib
    plt.gca().set_axis_off()
    plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
    plt.margins(0, 0)
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())
    plt.savefig(f"{image_name}.tmp.png", bbox_inches='tight', pad_inches=0, transparent=True) 
Example 6
Project: spatial_patterns   Author: sim-web   File: plotting.py    GNU General Public License v3.0 6 votes vote down vote up
def correlation_in_regions(self, region_size):
        for psp in self.psps:
            self.set_params_rawdata_computed(psp, set_sim_params=True)
            # Final frame after exploring the first half
            frame_in_half_1 = self.time2frame(self.boxside_switch_time,
                                              weight=True)
            # Final frame after exploring the second half
            frame_in_half_2 = self.time2frame(self.explore_all_time,
                                                   weight=True)
            frame_final = self.time2frame(self.simulation_time,
                                          weight=True)

            corr = self.get_correlation_of_final_grid_with_first_and_second_half(
                frame_in_half_1=frame_in_half_1,
                frame_in_half_2=frame_in_half_2,
                frame_final=frame_final,
                initial_side=self.boxside_initial_side,
                spacing=self.spacing,
                region_size=region_size
            )
            plt.plot(corr, marker='o', linestyle='none')
            plt.margins(0.1, 0.1) 
Example 7
Project: Trident-Segmentation-CNN   Author: YalongLiu   File: visualize.py    MIT License 6 votes vote down vote up
def display_images(images, titles=None, cols=4, cmap=None, norm=None,
                   interpolation=None):
    """Display the given set of images, optionally with titles.
    images: list or array of image tensors in HWC format.
    titles: optional. A list of titles to display with each image.
    cols: number of images per row
    cmap: Optional. Color map to use. For example, "Blues".
    norm: Optional. A Normalize instance to map values to colors.
    interpolation: Optional. Image interpolation to use for display.
    """
    titles = titles if titles is not None else [""] * len(images)
    rows = len(images) // cols + 1
    plt.figure(figsize=(14, 14 * rows // cols))
    plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
    plt.margins(0, 0)
    i = 1
    for image, title in zip(images, titles):
        plt.subplot(rows, cols, i)
        plt.title(title, fontsize=9)
        plt.axis('off')
        plt.imshow(image.astype(np.uint8), cmap=cmap,
                   norm=norm, interpolation=interpolation)
        i += 1
    plt.show() 
Example 8
Project: sul   Author: ddddwee1   File: sulplotter.py    Do What The F*ck You Want To Public License 6 votes vote down vote up
def __init__(self, usebuffer=False, elev=None, azim=None, axis='on', axis_tick='on', no_margin=False):
		fig = plt.figure()
		self.ax = fig.add_subplot(111, projection='3d')

		if no_margin:
			# axis = 'off'
			plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
			plt.margins(0,0,0)
			# self.ax.xaxis.set_major_locator(plt.NullLocator())
			# self.ax.yaxis.set_major_locator(plt.NullLocator())
		self.ax.view_init(elev=elev, azim=azim)
		self.ax.axis(axis)
		if axis_tick=='off':
			self.ax.set_xticklabels([])
			self.ax.set_yticklabels([])
			self.ax.set_zticklabels([])
		self.lines = []
		self.lines_buff = []
		self.line_pos = 0
		self.usebuffer = usebuffer
		self.fig = fig 
Example 9
Project: sul   Author: ddddwee1   File: sulplotter.py    Do What The F*ck You Want To Public License 6 votes vote down vote up
def __init__(self, usebuffer=False, elev=None, azim=None, axis='on', axis_tick='on', no_margin=False):
		fig = plt.figure()
		plt.tight_layout()
		self.ax = fig.add_subplot(111)
		if no_margin:
			axis = 'off'
			plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
			plt.margins(0,0)
			self.ax.xaxis.set_major_locator(plt.NullLocator())
			self.ax.yaxis.set_major_locator(plt.NullLocator())
		self.ax.axis(axis)
		if axis=='off':
			self.ax.set_xticklabels([])
			self.ax.set_yticklabels([])
		self.lines = []
		self.lines_buff = []
		self.line_pos = 0
		self.usebuffer = usebuffer
		self.fig = fig 
Example 10
Project: dvb.datascience   Author: devolksbank   File: ecdf.py    MIT License 6 votes vote down vote up
def transform_pandas(self, data: Data, params: Params) -> Data:
        df = data["df"]

        display(HTML("<h2>ECDF Plots Transform %s</h2>" % params["metadata"]["name"]))

        for feature in df.columns:
            fig = self.get_fig((1, feature))
            plt.plot(
                *self.ecdf(df[feature]),
                marker=".",
                linestyle="none",
                label=params["metadata"]["name"]
            )
            plt.title("ECDF of %s" % feature)
            plt.margins(0.02)
            plt.legend()
            plt.xlabel(feature)
            plt.ylabel("ECDF")
            display(fig)

        return {"figs": self.figs} 
Example 11
Project: dvb.datascience   Author: devolksbank   File: scatter.py    MIT License 6 votes vote down vote up
def transform_pandas(self, data: Data, params: Params) -> Data:
        display(HTML("<h2>Scatterplots Transform %s</h2>" % params["metadata"]["name"]))

        df = data["df"]
        for feature in df.columns:
            for feature2 in df.columns:
                if feature == feature2:
                    continue
                fig = self.get_fig((1, feature, feature2))
                plt.scatter(df[feature], df[feature2], label=params["metadata"]["name"])
                plt.title("Scatterplot of %s and %s" % (feature, feature2))
                plt.legend()
                plt.margins(0.02)
                plt.xlabel(feature)
                plt.ylabel(feature2)
                display(fig)

        return {"figs": self.figs} 
Example 12
Project: Refined-Segmentation-R-CNN   Author: YalongLiu   File: visualize.py    MIT License 6 votes vote down vote up
def display_images(images, titles=None, cols=4, cmap=None, norm=None,
                   interpolation=None):
    """Display the given set of images, optionally with titles.
    images: list or array of image tensors in HWC format.
    titles: optional. A list of titles to display with each image.
    cols: number of images per row
    cmap: Optional. Color map to use. For example, "Blues".
    norm: Optional. A Normalize instance to map values to colors.
    interpolation: Optional. Image interpolation to use for display.
    """
    titles = titles if titles is not None else [""] * len(images)
    rows = len(images) // cols + 1
    plt.figure(figsize=(14, 14 * rows // cols))
    plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
    plt.margins(0, 0)
    i = 1
    for image, title in zip(images, titles):
        plt.subplot(rows, cols, i)
        plt.title(title, fontsize=9)
        plt.axis('off')
        plt.imshow(image.astype(np.uint8), cmap=cmap,
                   norm=norm, interpolation=interpolation)
        i += 1
    plt.show() 
Example 13
Project: message-analyser   Author: vlajnaya-mol   File: plotter.py    MIT License 6 votes vote down vote up
def distplot_messages_per_hour(msgs, path_to_save):
    sns.set(style="whitegrid")

    ax = sns.distplot([msg.date.hour for msg in msgs], bins=range(25), color="m", kde=False)
    ax.set_xticklabels(stools.get_hours())
    ax.set(xlabel="hour", ylabel="messages")
    ax.margins(x=0)

    plt.xticks(range(24), rotation=65)
    plt.tight_layout()
    fig = plt.gcf()
    fig.set_size_inches(11, 8)

    fig.savefig(os.path.join(path_to_save, distplot_messages_per_hour.__name__ + ".png"), dpi=500)
    # plt.show()
    log_line(f"{distplot_messages_per_hour.__name__} was created.")
    plt.close("all") 
Example 14
Project: message-analyser   Author: vlajnaya-mol   File: plotter.py    MIT License 6 votes vote down vote up
def distplot_messages_per_day(msgs, path_to_save):
    sns.set(style="whitegrid")

    data = stools.get_messages_per_day(msgs)

    max_day_len = len(max(data.values(), key=len))
    ax = sns.distplot([len(day) for day in data.values()], bins=list(range(0, max_day_len, 50)) + [max_day_len],
                      color="m", kde=False)
    ax.set(xlabel="messages", ylabel="days")
    ax.margins(x=0)

    fig = plt.gcf()
    fig.set_size_inches(11, 8)

    fig.savefig(os.path.join(path_to_save, distplot_messages_per_day.__name__ + ".png"), dpi=500)
    # plt.show()
    log_line(f"{distplot_messages_per_day.__name__} was created.")
    plt.close("all") 
Example 15
Project: message-analyser   Author: vlajnaya-mol   File: plotter.py    MIT License 6 votes vote down vote up
def distplot_messages_per_month(msgs, path_to_save):
    sns.set(style="whitegrid")

    start_date = msgs[0].date.date()
    (xticks, xticks_labels, xlabel) = _get_xticks(msgs)

    ax = sns.distplot([(msg.date.date() - start_date).days for msg in msgs],
                      bins=xticks + [(msgs[-1].date.date() - start_date).days], color="m", kde=False)
    ax.set_xticklabels(xticks_labels)
    ax.set(xlabel=xlabel, ylabel="messages")
    ax.margins(x=0)

    plt.xticks(xticks, rotation=65)
    plt.tight_layout()
    fig = plt.gcf()
    fig.set_size_inches(11, 8)

    fig.savefig(os.path.join(path_to_save, distplot_messages_per_month.__name__ + ".png"), dpi=500)
    # plt.show()
    log_line(f"{distplot_messages_per_month.__name__} was created.")
    plt.close("all") 
Example 16
Project: hicstuff   Author: baudrly   File: vizmap.py    GNU General Public License v3.0 6 votes vote down vote up
def save_matrix(array, filename, vmax=None, dpi=DEFAULT_DPI):
    """A function that performs all the tedious matplotlib
    magic to draw a 2D array with as few parameters and
    as little whitespace as possible.

    Adjusted from https://github.com/koszullab/metaTOR
    """

    if vmax is None:
        vmax = np.percentile(array, DEFAULT_SATURATION_THRESHOLD)
    plt.gca().set_axis_off()
    plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
    plt.margins(0, 0)
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())
    plt.figure()
    if SEABORN:
        sns.heatmap(array, vmax=vmax, cmap="Reds")
    else:
        plt.imshow(array, vmax=vmax, cmap="Reds", interpolation="none")
        plt.colorbar()
    plt.axis("off")
    plt.savefig(filename, bbox_inches="tight", pad_inches=0.0, dpi=dpi)
    plt.close() 
Example 17
Project: BBMSG-GAN   Author: akanimax   File: generate_fid_plot.py    MIT License 6 votes vote down vote up
def generate_plot(x, y, title, save_path):
    """
    generates the plot given the indices and fid values
    :param x: the indices (epochs)
    :param y: fid values
    :param title: title of the generated plot
    :param save_path: path to save the file
    :return: None (saves file)
    """
    font = {'family': 'normal', 'size': 20}
    matplotlib.rc('font', **font)
    plt.figure(figsize=(10, 6))
    annot_min(x, y)
    plt.margins(.05, .05)
    plt.title(title)
    plt.xlabel("Epochs")
    plt.ylabel("FID scores")
    plt.plot(x, y, linewidth=4)
    plt.tight_layout()
    plt.savefig(save_path, bbox_inches='tight') 
Example 18
Project: BBMSG-GAN   Author: akanimax   File: generate_is_plot.py    MIT License 6 votes vote down vote up
def generate_plot(x, y, title, save_path):
    """
    generates the plot given the indices and is values
    :param x: the indices (epochs)
    :param y: IS values
    :param title: title of the generated plot
    :param save_path: path to save the file
    :return: None (saves file)
    """
    font = {'family': 'normal', 'size': 20}
    matplotlib.rc('font', **font)
    plt.figure(figsize=(10, 6))
    annot_max(x, y)
    plt.margins(.05, .05)
    plt.title(title)
    plt.xlabel("Epochs")
    plt.ylabel("Inception scores")
    plt.ylim(0, max(y) + 2)
    plt.plot(x, y, linewidth=4)
    plt.tight_layout()
    plt.savefig(save_path, bbox_inches='tight') 
Example 19
Project: honours_project   Author: JFriel   File: util.py    GNU General Public License v3.0 6 votes vote down vote up
def _show_plot(x_values, y_values, x_labels=None, y_labels=None):
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError('The plot function requires matplotlib to be installed.'
                         'See http://matplotlib.org/')

    plt.locator_params(axis='y', nbins=3)
    axes = plt.axes()
    axes.yaxis.grid()
    plt.plot(x_values, y_values, 'ro', color='red')
    plt.ylim(ymin=-1.2, ymax=1.2)
    plt.tight_layout(pad=5)
    if x_labels:
        plt.xticks(x_values, x_labels, rotation='vertical')
    if y_labels:
        plt.yticks([-1, 0, 1], y_labels, rotation='horizontal')
    # Pad margins so that markers are not clipped by the axes
    plt.margins(0.2)
    plt.show()

#////////////////////////////////////////////////////////////
#{ Parsing and conversion functions
#//////////////////////////////////////////////////////////// 
Example 20
Project: honours_project   Author: JFriel   File: util.py    GNU General Public License v3.0 6 votes vote down vote up
def _show_plot(x_values, y_values, x_labels=None, y_labels=None):
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError('The plot function requires matplotlib to be installed.'
                         'See http://matplotlib.org/')

    plt.locator_params(axis='y', nbins=3)
    axes = plt.axes()
    axes.yaxis.grid()
    plt.plot(x_values, y_values, 'ro', color='red')
    plt.ylim(ymin=-1.2, ymax=1.2)
    plt.tight_layout(pad=5)
    if x_labels:
        plt.xticks(x_values, x_labels, rotation='vertical')
    if y_labels:
        plt.yticks([-1, 0, 1], y_labels, rotation='horizontal')
    # Pad margins so that markers are not clipped by the axes
    plt.margins(0.2)
    plt.show()

#////////////////////////////////////////////////////////////
#{ Parsing and conversion functions
#//////////////////////////////////////////////////////////// 
Example 21
Project: aop-helpFinder   Author: jecarvaill   File: util.py    GNU General Public License v3.0 6 votes vote down vote up
def _show_plot(x_values, y_values, x_labels=None, y_labels=None):
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError('The plot function requires matplotlib to be installed.'
                         'See http://matplotlib.org/')

    plt.locator_params(axis='y', nbins=3)
    axes = plt.axes()
    axes.yaxis.grid()
    plt.plot(x_values, y_values, 'ro', color='red')
    plt.ylim(ymin=-1.2, ymax=1.2)
    plt.tight_layout(pad=5)
    if x_labels:
        plt.xticks(x_values, x_labels, rotation='vertical')
    if y_labels:
        plt.yticks([-1, 0, 1], y_labels, rotation='horizontal')
    # Pad margins so that markers are not clipped by the axes
    plt.margins(0.2)
    plt.show()

#////////////////////////////////////////////////////////////
#{ Parsing and conversion functions
#//////////////////////////////////////////////////////////// 
Example 22
Project: saapy   Author: ashapochka   File: plot_utils.py    Apache License 2.0 6 votes vote down vote up
def plot_ecdf(x, y, xlabel='attribute', legend='x'):
    """
    Plot distribution ECDF
    x should be sorted, y typically from 1/len(x) to 1

    TODO: function should be improved to plot multiple overlayed ecdfs
    """
    plt.plot(x, y, marker='.', linestyle='none')

    # Make nice margins
    plt.margins(0.02)

    # Annotate the plot
    plt.legend((legend,), loc='lower right')
    _ = plt.xlabel(xlabel)
    _ = plt.ylabel('ECDF')

    # Display the plot
    plt.show() 
Example 23
Project: SWHLab   Author: swharden   File: core.py    MIT License 6 votes vote down vote up
def comments(self,minutes=False):
        """
        Add comment lines/text to an existing plot. Defaults to seconds.
        Call after a plot has been made, and after margins have been set.
        """
        if self.comments==0:
            return
        self.log.debug("adding comments to plot")
        for i,t in enumerate(self.abf.comment_times):
            if minutes:
                t/=60.0
            plt.axvline(t,color='r',ls=':')
            X1,X2,Y1,Y2=plt.axis()
            Y2=Y2-abs(Y2-Y1)*.02
            plt.text(t,Y2,self.abf.comment_tags[i],color='r',rotation='vertical',
                     ha='right',va='top',weight='bold',alpha=.5,size=8,) 
Example 24
Project: SWHLab   Author: swharden   File: core.py    MIT License 6 votes vote down vote up
def decorate(self,show=False,protocol=False):
        self.log.debug("decorating")
        if self.title:
            plt.title("{}".format(self.abf.ID))
        plt.xlabel("seconds")
        if protocol:
            plt.ylabel(self.abf.protoUnits2)
        else:
            plt.ylabel(self.abf.units2)
        if self.gridAlpha:
            plt.grid(alpha=self.gridAlpha)
        plt.margins(self.marginX,self.marginY)
        plt.tight_layout()
        if show:
            plt.show()

    ### figure creation 
Example 25
Project: SWHLab   Author: swharden   File: protocols.py    MIT License 6 votes vote down vote up
def proto_0101(theABF):
    abf=ABF(theABF)
    abf.log.info("analyzing as an IC tau")
    #plot=ABFplot(abf)

    plt.figure(figsize=(SQUARESIZE/2,SQUARESIZE/2))
    plt.grid()
    plt.ylabel("relative potential (mV)")
    plt.xlabel("time (sec)")
    m1,m2=[.05,.1]
    for sweep in range(abf.sweeps):
        abf.setsweep(sweep)
        plt.plot(abf.sweepX2,abf.sweepY-abf.average(m1,m2),alpha=.2,color='#AAAAFF')
    average=abf.averageSweep()
    average-=np.average(average[int(m1**abf.pointsPerSec):int(m2*abf.pointsPerSec)])
    plt.plot(abf.sweepX2,average,color='b',lw=2,alpha=.5)
    plt.axvspan(m1,m2,color='r',ec=None,alpha=.1)
    plt.axhline(0,color='r',ls="--",alpha=.5,lw=2)
    plt.margins(0,.1)

    # save it
    plt.tight_layout()
    frameAndSave(abf,"IC tau")
    plt.close('all') 
Example 26
Project: SWHLab   Author: swharden   File: runtests.py    MIT License 6 votes vote down vote up
def test_0021_detectAndPlot2(self):
        abf=swhlab.ABF(testAbfPath)
        APs=swhlab.AP(abf)
        APs.detect()        
        Xs=APs.get_bySweep("times")
        Ys=APs.get_bySweep("freqs")        
        plt.figure(figsize=(10,8))
        for sweep in range(abf.sweeps):
            if not len(Ys[sweep]):
                continue
            abf.setsweep(sweep)            
            plt.subplot(212)
            plt.plot(Xs[sweep][1:],Ys[sweep],'.',alpha=.5,label="sweep %d"%sweep,ms=10)
            plt.subplot(211)
            plt.plot(abf.sweepX2,abf.sweepY,alpha=.5)
        plt.ylabel(abf.units2)
        plt.subplot(212)
        plt.grid(alpha=.5)
        plt.legend(loc=3)
        plt.margins(.1,.1)
        plt.ylabel("frequency (Hz)")
        plt.xlabel("time (seconds)")
        plt.tight_layout()
        plt.savefig('./output/APsFreqs.jpg')
        plt.close('all') 
Example 27
Project: Pixel2MeshPlusPlus   Author: walsvid   File: visualize.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_scatter(pt, data_name, plt_path):
    fig = plt.figure()
    fig.set_size_inches(20.0 / 3, 20.0 / 3)
    ax = fig.gca(projection='3d')
    ax.set_aspect('equal')
    ax.grid(color='r', linestyle='-',)
    ax.set_yticklabels([])
    ax.set_xticklabels([])
    ax.set_zticklabels([])
    X = pt[:, 0]
    Y = pt[:, 1]
    Z = pt[:, 2]

    scat = ax.scatter(X, Y, Z, depthshade=True, marker='.')

    max_range = np.array([X.max() - X.min(), Y.max() - Y.min(), Z.max() - Z.min()]).max() / 2.0

    mid_x = (X.max() + X.min()) * 0.5
    mid_y = (Y.max() + Y.min()) * 0.5
    mid_z = (Z.max() + Z.min()) * 0.5
    ax.set_xlim(mid_x - max_range, mid_x + max_range)
    ax.set_ylim(mid_y - max_range, mid_y + max_range)
    ax.set_zlim(mid_z - max_range, mid_z + max_range)

    plt.margins(0, 0)
    fig.savefig(os.path.join(plt_path, data_name.replace('.dat', '.png')), format='png', transparent=True, dpi=300, pad_inches=0, bbox_inches='tight') 
Example 28
Project: ves_ajoros   Author: ajoros   File: figures.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def initFigure(self):
        # Plot out the results
        plt.semilogy(self.voltageSpacingExtrapolated,
                     self.filteredResistivity,
                     marker=self.marker,
                     linestyle=self.linestyle,
                     color=self.colors[0],
                     label="Filtered")
        plt.semilogy(self.voltageSpacing, self.apparentResistivity,
                     marker=self.marker,
                     linestyle=self.linestyle,
                     color=self.colors[1],
                     label="Observed")
        plt.legend()

        # Create an mpl axis and set the labels, add the rectangle
        self.ax = plt.gca()
        self.ax.set_xlabel(self.xlabel)
        self.ax.set_ylabel(self.ylabel)
        self.ax.margins(0.5)

        # self.ax.add_patch(self.rect)
        self.ax.figure.canvas.draw()

        # Update the figure object/property
        self.fig = plt.gcf()

        self.fig.tight_layout() 
Example 29
Project: dvb.datascience   Author: devolksbank   File: hist.py    MIT License 5 votes vote down vote up
def transform_pandas(self, data: Data, params: Params) -> Data:
        df = data["df"].copy()

        display(
            HTML("<h4>%s Transform %s</h4>" % (self.title, params["metadata"]["name"]))
        )

        unique_group_by_values=  [i for i in df[self.group_by].unique()] if self.group_by else []

        for column in df.columns:
            column_data: List[pd.Series] = []
            if self.group_by is None or column == self.group_by:
                column_data = [df[column]]
                column_labels = [column]
            else:
                column_data = [df[df[self.group_by] == l][column] for l in unique_group_by_values]
                column_labels = list(unique_group_by_values)

            fig = self.get_fig((1, column, params["metadata"]["nr"]))
            for idx, d in enumerate(column_data):
                (values, bins, _) = plt.hist(d, label=[column_labels[idx]], alpha=0.5)
            plt.title(
                "%s (feature %s, transform %s)"
                % (self.title, column, params["metadata"]["name"])
            )
            plt.legend()
            plt.margins(0.1)
            plt.ylabel("Value")

            if self.show_count_labels:
                for i in range(len(values)):
                    if values[i] > 0:
                        plt.text(
                            bins[i], values[i] + 0.5, str(values[i])
                        )  # 0.5 added for offset values

            display(fig)

        return {"figs": self.figs} 
Example 30
Project: dvb.datascience   Author: devolksbank   File: hist.py    MIT License 5 votes vote down vote up
def transform_dask(self, data: Data, params: Params) -> Data:
        df = data["df"]

        display(
            HTML("<h4>%s Transform %s</h4>" % (self.title, params["metadata"]["name"]))
        )

        unique_group_by_values: List[Any] = []
        if self.group_by:
            unique_group_by_values = [i for i in df[self.group_by].unique().compute()]

        for column in df.columns:
            column_data: List[pd.Series] = []
            if self.group_by is None or column == self.group_by:
                column_data = [df[column].compute()]
                column_labels = [column]
            else:
                column_data = [df[df[self.group_by] == l][column].compute() for l in unique_group_by_values]
                column_labels = list(unique_group_by_values)

            fig = self.get_fig((1, column, params["metadata"]["nr"]))
            for idx, d in enumerate(column_data):
                (values, bins, _) = plt.hist(d, label=[column_labels[idx]], alpha=0.5)
            plt.title(
                "%s (feature %s, transform %s)"
                % (self.title, column, params["metadata"]["name"])
            )
            plt.legend()
            plt.margins(0.1)
            plt.ylabel("Value")

            if self.show_count_labels:
                for i in range(len(values)):
                    if values[i] > 0:
                        plt.text(
                            bins[i], values[i] + 0.5, str(values[i])
                        )  # 0.5 added for offset values

            display(fig)

        return {"figs": self.figs} 
Example 31
Project: dvb.datascience   Author: devolksbank   File: corrmatrix.py    MIT License 5 votes vote down vote up
def transform_pandas(self, data: Data, params: Params) -> Data:
        df = data["df"]
        labels = df.columns

        display(
            HTML(
                "<h2>Correlation Matrix Transform %s</h2>" % params["metadata"]["name"]
            )
        )

        corr = df.corr()

        fig = self.get_fig((params["metadata"]["name"]))

        fig.set_size_inches(5 + int(len(labels) * 0.3), 5 + int(len(labels) * 0.3))

        axes = plt.gca()

        plt.title("Correlation Matrix")
        plt.margins(0.02)

        myimage = axes.imshow(corr, cmap=plt.cm.get_cmap("bwr"), vmin=-1, vmax=1)

        # create axes on the right side of ax. The width of cax will be 5%
        # of ax and the padding between cax and ax will be fixed at 0.05 inch.
        divider = make_axes_locatable(axes)
        cax = divider.append_axes("right", size="5%", pad=0.05)

        plt.colorbar(myimage, cmap=plt.cm.get_cmap("bwr"), cax=cax)

        axes.set_xticks(np.arange(0, corr.shape[0], corr.shape[0] / len(labels)))
        axes.set_yticks(np.arange(0, corr.shape[1], corr.shape[1] / len(labels)))

        axes.set_xticklabels(labels, rotation=90)
        axes.set_yticklabels(labels)

        display(fig)

        return {"fig": fig, "corr": corr} 
Example 32
Project: labelKeypoint   Author: Jeff-sjtu   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def draw_label(label, img, label_names, colormap=None):
    plt.subplots_adjust(left=0, right=1, top=1, bottom=0,
                        wspace=0, hspace=0)
    plt.margins(0, 0)
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())

    if colormap is None:
        colormap = label_colormap(len(label_names))

    label_viz = label2rgb(label, img, n_labels=len(label_names))
    plt.imshow(label_viz)
    plt.axis('off')

    plt_handlers = []
    plt_titles = []
    for label_value, label_name in enumerate(label_names):
        fc = colormap[label_value]
        p = plt.Rectangle((0, 0), 1, 1, fc=fc)
        plt_handlers.append(p)
        plt_titles.append(label_name)
    plt.legend(plt_handlers, plt_titles, loc='lower right', framealpha=.5)

    f = io.BytesIO()
    plt.savefig(f, bbox_inches='tight', pad_inches=0)
    plt.cla()
    plt.close()

    out_size = (img.shape[1], img.shape[0])
    out = PIL.Image.open(f).resize(out_size, PIL.Image.BILINEAR).convert('RGB')
    out = np.asarray(out)
    return out 
Example 33
Project: RegRCNN   Author: MIC-DKFZ   File: plotting.py    Apache License 2.0 5 votes vote down vote up
def plot_batchgen_distribution(cf, pids, p_probs, balance_target, out_file=None):
    """plot top n_pids probabilities for drawing a pid into a batch.
    :param cf: experiment config object
    :param pids: sorted iterable of patient ids
    :param p_probs: pid's drawing likelihood, order needs to match the one of pids.
    :param out_file:
    :return:
    """
    n_pids = len(pids)
    zip_sorted = np.array(sorted(list(zip(p_probs, pids)), reverse=True))
    names, probs = zip_sorted[:n_pids,1], zip_sorted[:n_pids,0].astype('float32') * 100
    try:
        names = [str(int(n)) for n in names]
    except ValueError:
        names = [str(n) for n in names]
    lowest_p = min(p_probs)*100
    fig, ax = plt.subplots(1,1,figsize=(17,5), dpi=200)
    rects = ax.bar(names, probs, color=cf.blue, alpha=0.9, edgecolor=cf.blue)
    ax = plt.gca()
    ax.text(0.8, 0.92, "Lowest prob.: {:.5f}%".format(lowest_p), transform=ax.transAxes, color=cf.white,
            bbox=dict(boxstyle='round', facecolor=cf.blue, edgecolor='none', alpha=0.9))
    ax.yaxis.set_major_formatter(StrMethodFormatter('{x:g}'))
    ax.set_xticklabels(names, rotation="vertical", fontsize=7)
    plt.margins(x=0.01)
    plt.subplots_adjust(bottom=0.15)
    if balance_target=="class_targets":
        balance_target = "Class"
    elif balance_target=="lesion_gleasons":
        balance_target = "GS"
    ax.set_title(str(balance_target)+"-Balanced Train Generator: Sampling Likelihood per PID")
    ax.set_axisbelow(True)
    ax.grid(axis='y')
    ax.set_ylabel("Sampling Likelihood (%)")
    ax.set_xlabel("PID")
    plt.tight_layout()

    if out_file is not None:
        plt.savefig(out_file)

    plt.close() 
Example 34
Project: scikit-mechanics   Author: nasseralkmim   File: draw.py    GNU General Public License v3.0 5 votes vote down vote up
def draw_bc_dirichlet(displacement, model, name, dpi):

    plt.figure(name, dpi=dpi)

    h = model.AvgLength


    for line in displacement(1,1).keys():
        d= displacement(1,1)[line]
        if d[0] == 0.0 and d[1]== 0.0:
            for l, n1, n2 in model.nodes_in_bound_line:
                if line[1] == l:
                    x1 = model.XYZ[n1, 0]
                    y1 = model.XYZ[n1, 1]
                    plt.annotate('', xy=(x1, y1), xycoords='data',
                                 xytext=(x1-h,y1-h), textcoords='data',
                                 arrowprops=dict(facecolor='black', width=0.2,
                                                 headwidth=0.2))

                    x2 = model.XYZ[n2, 0]
                    y2 = model.XYZ[n2, 1]
                    plt.annotate('', xy=(x2, y2), xycoords='data',
                                 xytext=(x2-h,y2-h), textcoords='data',
                                 arrowprops=dict(facecolor='black', width=0.2,
                                                 headwidth=0.2))

    plt.axes().set_aspect('equal')

    plt.axes().autoscale_view(True, True, True)
    plt.margins(y=0.1, x=0.1, tight=False)
    plt.draw() 
Example 35
Project: scikit-mechanics   Author: nasseralkmim   File: draw.py    GNU General Public License v3.0 5 votes vote down vote up
def draw_bc_newmann(traction, model, name, dpi):

    plt.figure(name, dpi=dpi)

    h = model.AvgLength


    for line in traction(1,1).keys():
        t = traction(1,1)[line]
        if t[0] != 0.0 or t[1] != 0.0:
            for l, n1, n2 in model.nodes_in_bound_line:
                if line[1] == l:
                    x1 = model.XYZ[n1, 0]
                    y1 = model.XYZ[n1, 1]
                    t1 = traction(x1, y1)[line]
                    t_r1 = np.sqrt(t1[0]**2.+t1[1]**2.)
                    w=5000.0
                    plt.annotate('', xy=(x1, y1), xycoords='data',
                                 xytext=(x1 - t1[0]/w, y1 - t1[1]/w),
                                 textcoords='data', size=8,
                                 verticalalignment='top',
                                 arrowprops=dict(facecolor='black', width=0,
                                                 headwidth=4, shrink=0))

                    t_r2 = np.sqrt(t1[0]**2.+t1[1]**2.)
                    x2 = model.XYZ[n2, 0]
                    y2 = model.XYZ[n2, 1]
                    t2 = traction(x2, y2)[line]
                    plt.annotate('', xy=(x2, y2), xycoords='data',
                                 xytext=(x2 - t2[0]/w, y2 - t2[1]/w),
                                 textcoords='data', size=8,
                                 verticalalignment='top',
                                 arrowprops=dict(facecolor='black', width=0,
                                                 headwidth=4, shrink=0))
    plt.axes().set_aspect('equal')

    plt.axes().autoscale_view(True, True, True)
    plt.margins(y=0.1, x=0.1, tight=False)
    plt.draw() 
Example 36
Project: mask-rcnn-labelme   Author: wendelue   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def draw_label(label, img, label_names, colormap=None):
    plt.subplots_adjust(left=0, right=1, top=1, bottom=0,
                        wspace=0, hspace=0)
    plt.margins(0, 0)
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())

    if colormap is None:
        colormap = label_colormap(len(label_names))

    label_viz = label2rgb(label, img, n_labels=len(label_names))
    plt.imshow(label_viz)
    plt.axis('off')

    plt_handlers = []
    plt_titles = []
    for label_value, label_name in enumerate(label_names):
        fc = colormap[label_value]
        p = plt.Rectangle((0, 0), 1, 1, fc=fc)
        plt_handlers.append(p)
        plt_titles.append(label_name)
    plt.legend(plt_handlers, plt_titles, loc='lower right', framealpha=.5)

    f = io.BytesIO()
    plt.savefig(f, bbox_inches='tight', pad_inches=0)
    plt.cla()
    plt.close()

    out_size = (img.shape[1], img.shape[0])
    out = PIL.Image.open(f).resize(out_size, PIL.Image.BILINEAR).convert('RGB')
    out = np.asarray(out)
    return out 
Example 37
Project: dcase_task2   Author: CPJKU   File: plot_log.py    MIT License 5 votes vote down vote up
def tsplot(data, label=None, **kw):
    x = np.arange(data.shape[1])
    est = np.mean(data, axis=0)
    sd = np.std(data, axis=0)
    cis = (est - sd, est + sd)
    plt.fill_between(x, cis[0], cis[1], alpha=0.2, **kw)
    plt.plot(x, est, label=label, **kw)
    plt.margins(x=0) 
Example 38
Project: scikit-mechanics   Author: scikit-mechanics   File: draw.py    GNU General Public License v3.0 5 votes vote down vote up
def draw_bc_dirichlet(displacement, model, name, dpi):

    plt.figure(name, dpi=dpi)

    h = model.AvgLength


    for line in displacement(1,1).keys():
        d= displacement(1,1)[line]
        if d[0] == 0.0 and d[1]== 0.0:
            for l, n1, n2 in model.nodes_in_bound_line:
                if line[1] == l:
                    x1 = model.XYZ[n1, 0]
                    y1 = model.XYZ[n1, 1]
                    plt.annotate('', xy=(x1, y1), xycoords='data',
                                 xytext=(x1-h,y1-h), textcoords='data',
                                 arrowprops=dict(facecolor='black', width=0.2,
                                                 headwidth=0.2))

                    x2 = model.XYZ[n2, 0]
                    y2 = model.XYZ[n2, 1]
                    plt.annotate('', xy=(x2, y2), xycoords='data',
                                 xytext=(x2-h,y2-h), textcoords='data',
                                 arrowprops=dict(facecolor='black', width=0.2,
                                                 headwidth=0.2))

    plt.axes().set_aspect('equal')

    plt.axes().autoscale_view(True, True, True)
    plt.margins(y=0.1, x=0.1, tight=False)
    plt.draw() 
Example 39
Project: scikit-mechanics   Author: scikit-mechanics   File: draw.py    GNU General Public License v3.0 5 votes vote down vote up
def draw_bc_newmann(traction, model, name, dpi):

    plt.figure(name, dpi=dpi)

    h = model.AvgLength


    for line in traction(1,1).keys():
        t = traction(1,1)[line]
        if t[0] != 0.0 or t[1] != 0.0:
            for l, n1, n2 in model.nodes_in_bound_line:
                if line[1] == l:
                    x1 = model.XYZ[n1, 0]
                    y1 = model.XYZ[n1, 1]
                    t1 = traction(x1, y1)[line]
                    t_r1 = np.sqrt(t1[0]**2.+t1[1]**2.)
                    w=5000.0
                    plt.annotate('', xy=(x1, y1), xycoords='data',
                                 xytext=(x1 - t1[0]/w, y1 - t1[1]/w),
                                 textcoords='data', size=8,
                                 verticalalignment='top',
                                 arrowprops=dict(facecolor='black', width=0,
                                                 headwidth=4, shrink=0))

                    t_r2 = np.sqrt(t1[0]**2.+t1[1]**2.)
                    x2 = model.XYZ[n2, 0]
                    y2 = model.XYZ[n2, 1]
                    t2 = traction(x2, y2)[line]
                    plt.annotate('', xy=(x2, y2), xycoords='data',
                                 xytext=(x2 - t2[0]/w, y2 - t2[1]/w),
                                 textcoords='data', size=8,
                                 verticalalignment='top',
                                 arrowprops=dict(facecolor='black', width=0,
                                                 headwidth=4, shrink=0))
    plt.axes().set_aspect('equal')

    plt.axes().autoscale_view(True, True, True)
    plt.margins(y=0.1, x=0.1, tight=False)
    plt.draw() 
Example 40
Project: message-analyser   Author: vlajnaya-mol   File: plotter.py    MIT License 5 votes vote down vote up
def lineplot_messages(msgs, your_name, target_name, path_to_save):
    sns.set(style="whitegrid")

    (x, y_total), (xticks, xticks_labels, xlabel) = _get_plot_data(msgs), _get_xticks(msgs)

    y_your = [len([msg for msg in period if msg.author == your_name]) for period in y_total]
    y_target = [len([msg for msg in period if msg.author == target_name]) for period in y_total]

    plt.fill_between(x, y_your, alpha=0.3)
    ax = sns.lineplot(x=x, y=y_your, palette="denim blue", linewidth=2.5, label=your_name)
    plt.fill_between(x, y_target, alpha=0.3)
    sns.lineplot(x=x, y=y_target, linewidth=2.5, label=target_name)

    ax.set(xlabel=xlabel, ylabel="messages")
    ax.set_xticklabels(xticks_labels)

    ax.tick_params(axis='x', bottom=True, color="#A9A9A9")
    plt.xticks(xticks, rotation=65)
    ax.margins(x=0, y=0)

    # plt.tight_layout()
    fig = plt.gcf()
    fig.set_size_inches(13, 7)

    fig.savefig(os.path.join(path_to_save, lineplot_messages.__name__ + ".png"), dpi=500)
    # plt.show()
    plt.close("all")
    log_line(f"{lineplot_messages.__name__} was created.") 
Example 41
Project: metaTOR   Author: koszullab   File: figures.py    GNU General Public License v3.0 5 votes vote down vote up
def spaceless_pdf_plot_maker(array, filename, vmax=None, dpi=DEFAULT_DPI):
    """Draw a pretty plot from an array

    A function that performs all the tedious matplotlib
    magic to draw a 2D array with as few parameters and
    as little whitespace as possible.

    Parameters
    ----------
    array : array_like
        The input array to draw.
    filename : file, str or pathlib.Path
        The output image to save the array into.
    vmax : float, optional
        The default saturation threshold for the array. If set to None, the
        80th percentile value of the array is chosen. Default is None.
    dpi : int, optional
        Dots per inch (DPI) of the output image. Default is 200.
    """

    if vmax is None:
        vmax = np.percentile(array, DEFAULT_SATURATION_THRESHOLD)
    plt.gca().set_axis_off()
    plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
    plt.margins(0, 0)
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())
    plt.figure()
    if SEABORN:
        sns.heatmap(array, vmax=vmax, cmap="Reds")
    else:
        plt.imshow(array, vmax=vmax, cmap="Reds", interpolation="none")
        plt.colorbar()
    plt.savefig(filename, bbox_inches="tight", pad_inches=0.0, dpi=dpi)
    plt.close() 
Example 42
Project: BBMSG-GAN   Author: akanimax   File: generate_multiple_is_plots.py    MIT License 5 votes vote down vote up
def generate_plot(xs, ys, titles, save_path):
    """
    generates the plot given the indices and is values
    :param xs: the indices (epochs)
    :param ys: IS values
    :param titles: title of the generated plot
    :param save_path: path to save the file
    :return: None (saves file)
    """
    font = {'family': 'normal', 'size': 20}
    matplotlib.rc('font', **font)
    plt.figure(figsize=(10, 6))

    plt.xlabel("Epochs")
    plt.ylabel("Inception scores")

    # set the y limit to 4 + max of everything
    plt.ylim(0, max(map(max, ys)) + 5)

    for cnt, x, y, title in zip(range(len(xs)), xs, ys, titles):
        annot_max(x, y, y_offset=0.96 - (0.07 * cnt))
        plt.margins(.05, .05)
        plt.plot(x, y, linewidth=4, label=title)

    plt.legend(loc="upper left")
    plt.tight_layout()
    plt.savefig(save_path, bbox_inches='tight') 
Example 43
Project: BBMSG-GAN   Author: akanimax   File: generate_multiple_fid_plots.py    MIT License 5 votes vote down vote up
def generate_plot(xs, ys, titles, save_path):
    """
    generates the plot given the indices and is values
    :param xs: the indices (epochs)
    :param ys: FID values
    :param titles: title of the generated plot
    :param save_path: path to save the file
    :return: None (saves file)
    """
    font = {'family': 'normal', 'size': 20}
    matplotlib.rc('font', **font)
    plt.figure(figsize=(10, 6))

    plt.xlabel("Epochs")
    plt.ylabel("FID scores")

    # set the y limit to 4 + max of everything
    plt.ylim(0, max(map(max, ys)) + 50)

    for cnt, x, y, title in zip(range(len(xs)), xs, ys, titles):
        annot_min(x, y, y_offset=0.96 - (0.07 * cnt))
        plt.margins(.05, .05)
        plt.plot(x, y, linewidth=4, label=title)

    plt.legend(loc="upper left")
    plt.tight_layout()
    plt.savefig(save_path, bbox_inches='tight') 
Example 44
Project: smp_base   Author: x75   File: plot_utils.py    MIT License 5 votes vote down vote up
def savefig_plotonly():
    plt.axis('off')
    plt.gca().set_axis_off()
    plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, 
            hspace = 0, wspace = 0)
    plt.margins(0,0)
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())
    # savefig("filename.pdf", bbox_inches = 'tight', pad_inches = 0)
    # fig.savefig(inputFile.replace(".wav", "_thumb1.png"), dpi=300)
    fig.savefig(thumbnailWrapperFileName3Png, bbox_inches = 'tight', pad_inches = 0, dpi=300) 
Example 45
Project: elastopy   Author: nasseralkmim   File: draw.py    GNU General Public License v3.0 5 votes vote down vote up
def draw_bc_dirichlet(displacement, model, name, dpi):

    plt.figure(name, dpi=dpi)

    h = model.AvgLength


    for line in displacement(1,1).keys():
        d= displacement(1,1)[line]
        if d[0] == 0.0 and d[1]== 0.0:
            for l, n1, n2 in model.nodes_in_bound_line:
                if line[1] == l:
                    x1 = model.XYZ[n1, 0]
                    y1 = model.XYZ[n1, 1]
                    plt.annotate('', xy=(x1, y1), xycoords='data',
                                 xytext=(x1-h,y1-h), textcoords='data',
                                 arrowprops=dict(facecolor='black', width=0.2,
                                                 headwidth=0.2))

                    x2 = model.XYZ[n2, 0]
                    y2 = model.XYZ[n2, 1]
                    plt.annotate('', xy=(x2, y2), xycoords='data',
                                 xytext=(x2-h,y2-h), textcoords='data',
                                 arrowprops=dict(facecolor='black', width=0.2,
                                                 headwidth=0.2))

    plt.axes().set_aspect('equal')

    plt.axes().autoscale_view(True, True, True)
    plt.margins(y=0.1, x=0.1, tight=False)
    plt.draw() 
Example 46
Project: elastopy   Author: nasseralkmim   File: draw.py    GNU General Public License v3.0 5 votes vote down vote up
def draw_bc_newmann(traction, model, name, dpi):

    plt.figure(name, dpi=dpi)

    h = model.AvgLength


    for line in traction(1,1).keys():
        t = traction(1,1)[line]
        if t[0] != 0.0 or t[1] != 0.0:
            for l, n1, n2 in model.nodes_in_bound_line:
                if line[1] == l:
                    x1 = model.XYZ[n1, 0]
                    y1 = model.XYZ[n1, 1]
                    t1 = traction(x1, y1)[line]
                    t_r1 = np.sqrt(t1[0]**2.+t1[1]**2.)
                    w=5000.0
                    plt.annotate('', xy=(x1, y1), xycoords='data',
                                 xytext=(x1 - t1[0]/w, y1 - t1[1]/w),
                                 textcoords='data', size=8,
                                 verticalalignment='top',
                                 arrowprops=dict(facecolor='black', width=0,
                                                 headwidth=4, shrink=0))

                    t_r2 = np.sqrt(t1[0]**2.+t1[1]**2.)
                    x2 = model.XYZ[n2, 0]
                    y2 = model.XYZ[n2, 1]
                    t2 = traction(x2, y2)[line]
                    plt.annotate('', xy=(x2, y2), xycoords='data',
                                 xytext=(x2 - t2[0]/w, y2 - t2[1]/w),
                                 textcoords='data', size=8,
                                 verticalalignment='top',
                                 arrowprops=dict(facecolor='black', width=0,
                                                 headwidth=4, shrink=0))
    plt.axes().set_aspect('equal')

    plt.axes().autoscale_view(True, True, True)
    plt.margins(y=0.1, x=0.1, tight=False)
    plt.draw() 
Example 47
Project: The-Python-Graph-Gallery   Author: holtzy   File: PGG_notebook.py    MIT License 5 votes vote down vote up
def sankey(**value):
    """Show SankeyWidget with default values for size and margins""" 
Example 48
Project: gerrit-latency   Author: c-robin   File: gerrit-latency.py    Apache License 2.0 5 votes vote down vote up
def graph(x, y):
    """ This method allow to print a basic graph of 2 lists. The 2 lists must have the same size.

    Args:
        x (list of double): list of all abscissae of the points in a system of Cartesian coordinate
        y (list of double): list of all ordinates of the points in a system of Cartesian coordinate
    """
    plt.plot(x, y, 'ro')
    plt.margins(0.2)
    plt.subplots_adjust(bottom=0.15)
    plt.show() 
Example 49
Project: SWHLab   Author: swharden   File: protocols.py    MIT License 5 votes vote down vote up
def proto_0203(theABF):
    """protocol: vast IV."""
    abf=ABF(theABF)
    abf.log.info("analyzing as a fast IV")
    plot=ABFplot(abf)
    plot.title=""
    m1,m2=.7,1
    plt.figure(figsize=(SQUARESIZE,SQUARESIZE/2))

    plt.subplot(121)
    plot.figure_sweeps()
    plt.axvspan(m1,m2,color='r',ec=None,alpha=.1)

    plt.subplot(122)
    plt.grid(alpha=.5)
    Xs=np.arange(abf.sweeps)*5-110
    Ys=[]
    for sweep in range(abf.sweeps):
        abf.setsweep(sweep)
        Ys.append(abf.average(m1,m2))
    plt.plot(Xs,Ys,'.-',ms=10)
    plt.axvline(-70,color='r',ls='--',lw=2,alpha=.5)
    plt.axhline(0,color='r',ls='--',lw=2,alpha=.5)
    plt.margins(.1,.1)
    plt.xlabel("membrane potential (mV)")

    # save it
    plt.tight_layout()
    frameAndSave(abf,"fast IV")
    plt.close('all') 
Example 50
Project: SWHLab   Author: swharden   File: protocols.py    MIT License 5 votes vote down vote up
def proto_0911(theABF):
    abf=ABF(theABF)
    abf.log.info("analyzing as paired pulse stimulation with various increasing ISIs")
    plt.figure(figsize=(8,8))
    M1,M2=2.2,2.4
    I1,I2=int(M1*abf.pointsPerSec),int(M2*abf.pointsPerSec)
    Ip1=int(2.23440*abf.pointsPerSec) # time of first pulse in the sweep
    pw=int(1.5/1000*abf.pointsPerSec) # pulse width in ms
    B1,B2=1,2 # baseline time in seconds
    plt.axhline(0,alpha=.5,ls='--',lw=2,color='k')
    for sweep in range(abf.sweeps):
        abf.setsweep(sweep)
        Xs=abf.sweepX2[I1:I2]*1000
        baseline=np.average(abf.sweepY[int(B1*abf.pointsPerSec):int(B2*abf.pointsPerSec)])
        Ys=abf.sweepY[I1:I2]-baseline
        Ys[Ip1-I1:Ip1-I1+pw]=np.nan # erase the first pulse
        isi=int(10+sweep*10) # interspike interval (ms)
        Ip2d = int(isi/1000*abf.pointsPerSec)
        Ys[Ip1-I1+Ip2d:Ip1-I1+pw+Ip2d]=np.nan # erase the second pulse
        plt.plot(Xs-Xs[0],Ys,alpha=.8,label="%d ms"%isi)
    plt.margins(0,.1)
    plt.legend()
    plt.grid(alpha=.4,ls='--')
    plt.title("Paired Pulse Stimuation (varied ISIs)")
    plt.ylabel("clamp current (pA) [artifacts removed]")
    plt.xlabel("time (ms) [offset by %.02f s]"%M1)
    plt.tight_layout()
    frameAndSave(abf,"pp_varied")
    plt.close('all')