Python matplotlib.cbook.get_sample_data() Examples

The following are 22 code examples of matplotlib.cbook.get_sample_data(). 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.cbook , or try the search function .
Example #1
Source File: test_colors.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_light_source_topo_surface():
    """Shades a DEM using different v.e.'s and blend modes."""
    fname = cbook.get_sample_data('jacksboro_fault_dem.npz', asfileobj=False)
    dem = np.load(fname)
    elev = dem['elevation']
    # Get the true cellsize in meters for accurate vertical exaggeration
    #   Convert from decimal degrees to meters
    dx, dy = dem['dx'], dem['dy']
    dx = 111320.0 * dx * np.cos(dem['ymin'])
    dy = 111320.0 * dy
    dem.close()

    ls = mcolors.LightSource(315, 45)
    cmap = cm.gist_earth

    fig, axes = plt.subplots(nrows=3, ncols=3)
    for row, mode in zip(axes, ['hsv', 'overlay', 'soft']):
        for ax, ve in zip(row, [0.1, 1, 10]):
            rgb = ls.shade(elev, cmap, vert_exag=ve, dx=dx, dy=dy,
                           blend_mode=mode)
            ax.imshow(rgb)
            ax.set(xticks=[], yticks=[]) 
Example #2
Source File: test_colors.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def test_light_source_topo_surface():
    """Shades a DEM using different v.e.'s and blend modes."""
    fname = cbook.get_sample_data('jacksboro_fault_dem.npz', asfileobj=False)
    dem = np.load(fname)
    elev = dem['elevation']
    # Get the true cellsize in meters for accurate vertical exaggeration
    #   Convert from decimal degrees to meters
    dx, dy = dem['dx'], dem['dy']
    dx = 111320.0 * dx * np.cos(dem['ymin'])
    dy = 111320.0 * dy
    dem.close()

    ls = mcolors.LightSource(315, 45)
    cmap = cm.gist_earth

    fig, axes = plt.subplots(nrows=3, ncols=3)
    for row, mode in zip(axes, ['hsv', 'overlay', 'soft']):
        for ax, ve in zip(row, [0.1, 1, 10]):
            rgb = ls.shade(elev, cmap, vert_exag=ve, dx=dx, dy=dy,
                           blend_mode=mode)
            ax.imshow(rgb)
            ax.set(xticks=[], yticks=[]) 
Example #3
Source File: aggregation_api.py    From aggregation with Apache License 2.0 6 votes vote down vote up
def __plot_image__(self,subject_id,axes):
        # TODO - still learning about Matplotlib and axes
        # see http://matplotlib.org/users/artists.html
        fname = self.__image_setup__(subject_id)

        exception = None
        for i in range(10):
            try:
                # fig = plt.figure()
                # ax = fig.add_subplot(1, 1, 1)
                image_file = cbook.get_sample_data(fname)
                image = plt.imread(image_file)
                # fig, ax = plt.subplots()
                im = axes.imshow(image)

                return self.__get_subject_dimension__(subject_id)
            except IOError as e:
                # try downloading that image again
                os.remove(fname)
                self.__image_setup__(subject_id)
                exception = e

        raise exception or Exception('Failed to plot image') 
Example #4
Source File: aggregation.py    From aggregation with Apache License 2.0 6 votes vote down vote up
def __display__markings__(self, zooniverse_id):
        assert zooniverse_id in self.clusterResults
        subject = self.subject_collection.find_one({"zooniverse_id": zooniverse_id})
        zooniverse_id = subject["zooniverse_id"]
        print zooniverse_id
        url = subject["location"]["standard"]

        slash_index = url.rfind("/")
        object_id = url[slash_index+1:]

        if not(os.path.isfile(base_directory+"/Databases/"+self.project+"/images/"+object_id)):
            urllib.urlretrieve(url, base_directory+"/Databases/"+self.project+"/images/"+object_id)

        image_file = cbook.get_sample_data(base_directory+"/Databases/"+self.project+"/images/"+object_id)
        image = plt.imread(image_file)

        fig, ax = plt.subplots()
        im = ax.imshow(image)

        for (x, y), pts, users in zip(*self.clusterResults[zooniverse_id]):
            plt.plot([x, ], [y, ], 'o', color="red")


        plt.show()
        plt.close() 
Example #5
Source File: shading_example.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    # Test data
    x, y = np.mgrid[-5:5:0.05, -5:5:0.05]
    z = 5 * (np.sqrt(x**2 + y**2) + np.sin(x**2 + y**2))

    filename = get_sample_data('jacksboro_fault_dem.npz', asfileobj=False)
    with np.load(filename) as dem:
        elev = dem['elevation']

    fig = compare(z, plt.cm.copper)
    fig.suptitle('HSV Blending Looks Best with Smooth Surfaces', y=0.95)

    fig = compare(elev, plt.cm.gist_earth, ve=0.05)
    fig.suptitle('Overlay Blending Looks Best with Rough Surfaces', y=0.95)

    plt.show() 
Example #6
Source File: test_colors.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def test_light_source_topo_surface():
    """Shades a DEM using different v.e.'s and blend modes."""
    fname = cbook.get_sample_data('jacksboro_fault_dem.npz', asfileobj=False)
    dem = np.load(fname)
    elev = dem['elevation']
    # Get the true cellsize in meters for accurate vertical exaggeration
    #   Convert from decimal degrees to meters
    dx, dy = dem['dx'], dem['dy']
    dx = 111320.0 * dx * np.cos(dem['ymin'])
    dy = 111320.0 * dy
    dem.close()

    ls = mcolors.LightSource(315, 45)
    cmap = cm.gist_earth

    fig, axes = plt.subplots(nrows=3, ncols=3)
    for row, mode in zip(axes, ['hsv', 'overlay', 'soft']):
        for ax, ve in zip(row, [0.1, 1, 10]):
            rgb = ls.shade(elev, cmap, vert_exag=ve, dx=dx, dy=dy,
                           blend_mode=mode)
            ax.imshow(rgb)
            ax.set(xticks=[], yticks=[]) 
Example #7
Source File: demo_colorbar_of_inset_axes.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_demo_image():
    from matplotlib.cbook import get_sample_data
    import numpy as np
    f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
    z = np.load(f)
    # z is a numpy array of 15x15
    return z, (-3, 4, -4, 3) 
Example #8
Source File: demo_axes_rgb.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_demo_image():
    from matplotlib.cbook import get_sample_data
    f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
    z = np.load(f)
    # z is a numpy array of 15x15
    return z, (-3, 4, -4, 3) 
Example #9
Source File: demo_axes_divider.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_demo_image():
    import numpy as np
    from matplotlib.cbook import get_sample_data
    f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
    z = np.load(f)
    # z is a numpy array of 15x15
    return z, (-3, 4, -4, 3) 
Example #10
Source File: simple_rgb.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_demo_image():
    import numpy as np
    from matplotlib.cbook import get_sample_data
    f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
    z = np.load(f)
    # z is a numpy array of 15x15
    return z, (-3, 4, -4, 3) 
Example #11
Source File: demo_axes_grid.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_demo_image():
    import numpy as np
    from matplotlib.cbook import get_sample_data
    f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
    z = np.load(f)
    # z is a numpy array of 15x15
    return z, (-3, 4, -4, 3) 
Example #12
Source File: simple_axesgrid2.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_demo_image():
    import numpy as np
    from matplotlib.cbook import get_sample_data
    f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
    z = np.load(f)
    # z is a numpy array of 15x15
    return z, (-3, 4, -4, 3) 
Example #13
Source File: ouroboros_api.py    From aggregation with Apache License 2.0 5 votes vote down vote up
def __display_image__(self,subject_id,args_l,kwargs_l,block=True,title=None):
        """
        return the file names for all the images associated with a given subject_id
        also download them if necessary
        :param subject_id:
        :return:
        """
        subject = self.subject_collection.find_one({"zooniverse_id": subject_id})
        url = subject["location"]["standard"]

        slash_index = url.rfind("/")
        object_id = url[slash_index+1:]

        if not(os.path.isfile(self.base_directory+"/Databases/"+self.project+"/images/"+object_id)):
            urllib.urlretrieve(url, self.base_directory+"/Databases/"+self.project+"/images/"+object_id)

        fname = self.base_directory+"/Databases/"+self.project+"/images/"+object_id

        image_file = cbook.get_sample_data(fname)
        image = plt.imread(image_file)

        fig, ax = plt.subplots()
        im = ax.imshow(image,cmap = cm.Greys_r)

        for args,kwargs in zip(args_l,kwargs_l):
            print args,kwargs
            ax.plot(*args,**kwargs)

        if title is not None:
            ax.set_title(title)
        plt.show(block=block) 
Example #14
Source File: aggregation.py    From aggregation with Apache License 2.0 5 votes vote down vote up
def __display_image__(self,zooniverse_id):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            fname = self.__get_image_fname__(zooniverse_id)

            image_file = cbook.get_sample_data(fname)
            image = plt.imread(image_file)

            fig, ax = plt.subplots()
            im = ax.imshow(image) 
Example #15
Source File: demo_edge_colorbar.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_demo_image():
    import numpy as np
    from matplotlib.cbook import get_sample_data
    f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
    z = np.load(f)
    # z is a numpy array of 15x15
    return z, (-3, 4, -4, 3) 
Example #16
Source File: aggregation.py    From aggregation with Apache License 2.0 5 votes vote down vote up
def __save_raw_markings__(self,zooniverse_id):
        self.__display_image__(zooniverse_id)
        print "Num users: " + str(len(self.users_per_subject[zooniverse_id]))
        X,Y = zip(*self.markings_list[zooniverse_id])
        plt.plot(X,Y,'.')
        plt.xlim((0,1000))
        plt.ylim((563,0))
        plt.xticks([])
        plt.yticks([])
        plt.savefig(base_directory+"/Databases/"+self.project+"/examples/"+zooniverse_id+".pdf",bbox_inches='tight')
        plt.close()

    # def __display_image__(self,zooniverse_id):
    #     #assert zooniverse_id in self.clusterResults
    #     subject = self.subject_collection.find_one({"zooniverse_id": zooniverse_id})
    #     zooniverse_id = subject["zooniverse_id"]
    #     #print zooniverse_id
    #     url = subject["location"]["standard"]
    #
    #     slash_index = url.rfind("/")
    #     object_id = url[slash_index+1:]
    #
    #     if not(os.path.isfile(base_directory+"/Databases/"+self.project+"/images/"+object_id)):
    #         urllib.urlretrieve(url, base_directory+"/Databases/"+self.project+"/images/"+object_id)
    #
    #     image_file = cbook.get_sample_data(base_directory+"/Databases/"+self.project+"/images/"+object_id)
    #     image = plt.imread(image_file)
    #
    #     fig, ax = plt.subplots()
    #     im = ax.imshow(image)
    #     plt.xlim((0,1000))
    #     plt.ylim((563,0)) 
Example #17
Source File: inset_locator_demo2.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_demo_image():
    from matplotlib.cbook import get_sample_data
    import numpy as np
    f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
    z = np.load(f)
    # z is a numpy array of 15x15
    return z, (-3, 4, -4, 3) 
Example #18
Source File: backup_weather.py    From aggregation with Apache License 2.0 5 votes vote down vote up
def __plot__(self,fname):
        image_file = cbook.get_sample_data(fname)
        image = plt.imread(image_file)

        fig, ax1 = plt.subplots(1, 1)
        fig.set_size_inches(52,78)
        ax1.imshow(image)

        horiz_segments,vert_segments,horiz_intercepts,vert_intercepts = self.__get_grid_segments__()
        h_lines = self.__segments_to_grids__(horiz_segments,horiz_intercepts,horiz=True)
        v_lines = self.__segments_to_grids__(vert_segments,vert_intercepts,horiz=False)


        for (lb,ub) in h_lines:
            X,Y = zip(*lb)
            ax1.plot(X, Y,color="blue")
            X,Y = zip(*ub)
            ax1.plot(X, Y,color="blue")

        for (lb,ub) in v_lines:
            X,Y = zip(*lb)
            ax1.plot(X, Y,color="blue")
            X,Y = zip(*ub)
            ax1.plot(X, Y,color="blue")

        plt.savefig("/home/ggdhines/Databases/temp.jpg",bbox_inches='tight', pad_inches=0,dpi=72) 
Example #19
Source File: whales.py    From aggregation with Apache License 2.0 5 votes vote down vote up
def convex_hull(points):
    """Computes the convex hull of a set of 2D points.

    Input: an iterable sequence of (x, y) pairs representing the points.
    Output: a list of vertices of the convex hull in counter-clockwise order,
      starting from the vertex with the lexicographically smallest coordinates.
    Implements Andrew's monotone chain algorithm. O(n log n) complexity.
    """

    # Sort the points lexicographically (tuples are compared lexicographically).
    # Remove duplicates to detect the case we have just one unique point.
    points = sorted(list(set(points)))

    # Boring case: no points or a single point, possibly repeated multiple times.
    if len(points) <= 1:
        return points

    # 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product.
    # Returns a positive value, if OAB makes a counter-clockwise turn,
    # negative for clockwise turn, and zero if the points are collinear.
    def cross(o, a, b):
        return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])


    lower = []
    for p in points:
        while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
            lower.pop()
        lower.append(p)

    # Concatenation of the lower and upper hulls gives the convex hull.
    # Last point of each list is omitted because it is repeated at the beginning of the other list.
    return lower

# image_file = cbook.get_sample_data("/home/ggdhines/Databases/images/2fe9c6d0-4b1b-49a4-a96e-15e1cace73b8.jpeg") 
Example #20
Source File: divisiveDBSCAN.py    From aggregation with Apache License 2.0 4 votes vote down vote up
def fit(self, markings,user_ids,jpeg_file=None,debug=False):
        #start by creating the initial "super" cluster
        end_clusters = []
        clusters_to_go = [(markings[:],user_ids[:],self.starting_epsilon),]
        total_noise = {}
        total_noise2 = []

        if jpeg_file is not None:
            image_file = cbook.get_sample_data(jpeg_file)
            image = plt.imread(image_file)
            fig, ax = plt.subplots()
            im = ax.imshow(image)

            x,y = zip(*markings)
            plt.plot(x,y,'o',color="green")
            plt.xlim(0,1000)
            plt.ylim(748,0)
            plt.show()

        while True:
            #if we have run out of clusters to process, break (hopefully done :) )
            if clusters_to_go == []:
                break
            m_,u_,e_ = clusters_to_go.pop(0)

            noise_found,final,to_split = self.binary_search_DBSCAN(m_,u_,e_,jpeg_file)
            #print to_split
            #print e_
            #print noise
            #print "=== " + str(noise_found)
            if noise_found != []:
                #print "==="

                for p,u in noise_found:
                    total_noise2.append(p)
                    assert(type(p) == tuple)
                    if not(u in total_noise):
                        total_noise[u] = [p]
                    else:
                        total_noise[u].append(p)
            #total_noise.extend(noise)
            end_clusters.extend(final[:])
            clusters_to_go.extend(to_split[:])

            #break

        cluster_centers = []
        for cluster in end_clusters:
            x,y = zip(*cluster)
            cluster_centers.append((np.mean(x),np.mean(y)))
        #print total_noise
        #print "===="

        if debug:
            return cluster_centers, end_clusters,total_noise2
        else:
            return cluster_centers 
Example #21
Source File: ABuMLExecute.py    From abu with GNU General Public License v3.0 4 votes vote down vote up
def graphviz_tree(estimator, features, x, y):
    """
    绘制决策树或者core基于树的分类回归算法的决策示意图绘制,查看
    学习器本身hasattr(fiter, 'tree_')是否有tree_属性,内部clone(estimator)学习器
    后再进行训练操作,完成训练后使用sklearn中tree.export_graphvizd导出graphviz.dot文件
    需要使用第三方dot工具将graphviz.dot进行转换graphviz.png,即内部实行使用
    运行命令行:
                os.system("dot -T png graphviz.dot -o graphviz.png")
    最后读取决策示意图显示

    :param estimator: 学习器对象,透传learning_curve
    :param x: 训练集x矩阵,numpy矩阵
    :param y: 训练集y序列,numpy序列
    :param features: 训练集x矩阵列特征所队员的名称,可迭代序列对象
    """
    if not hasattr(estimator, 'tree_'):
        logging.info('only tree can graphviz!')
        return

    # 所有执行fit的操作使用clone一个新的
    estimator = clone(estimator)
    estimator.fit(x, y)
    # TODO out_file path放倒cache中
    tree.export_graphviz(estimator.tree_, out_file='graphviz.dot', feature_names=features)
    os.system("dot -T png graphviz.dot -o graphviz.png")

    '''
        !open $path
        要是方便用notebook直接open其实显示效果好,plt,show的大小不好调整
    '''
    graphviz = os.path.join(os.path.abspath('.'), 'graphviz.png')

    # path = graphviz
    # !open $path
    if not file_exist(graphviz):
        logging.info('{} not exist! please install dot util!'.format(graphviz))
        return

    image_file = cbook.get_sample_data(graphviz)
    image = plt.imread(image_file)
    image_file.close()
    plt.imshow(image)
    plt.axis('off')  # clear x- and y-axes
    plt.show() 
Example #22
Source File: embedding_in_wx3_sgskip.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def OnInit(self):
        xrcfile = cbook.get_sample_data('embedding_in_wx3.xrc',
                                        asfileobj=False)
        print('loading', xrcfile)

        self.res = xrc.XmlResource(xrcfile)

        # main frame and panel ---------

        self.frame = self.res.LoadFrame(None, "MainFrame")
        self.panel = xrc.XRCCTRL(self.frame, "MainPanel")

        # matplotlib panel -------------

        # container for matplotlib panel (I like to make a container
        # panel for our panel so I know where it'll go when in XRCed.)
        plot_container = xrc.XRCCTRL(self.frame, "plot_container_panel")
        sizer = wx.BoxSizer(wx.VERTICAL)

        # matplotlib panel itself
        self.plotpanel = PlotPanel(plot_container)
        self.plotpanel.init_plot_data()

        # wx boilerplate
        sizer.Add(self.plotpanel, 1, wx.EXPAND)
        plot_container.SetSizer(sizer)

        # whiz button ------------------
        whiz_button = xrc.XRCCTRL(self.frame, "whiz_button")
        whiz_button.Bind(wx.EVT_BUTTON, self.plotpanel.OnWhiz)

        # bang button ------------------
        bang_button = xrc.XRCCTRL(self.frame, "bang_button")
        bang_button.Bind(wx.EVT_BUTTON, self.OnBang)

        # final setup ------------------
        sizer = self.panel.GetSizer()
        self.frame.Show(1)

        self.SetTopWindow(self.frame)

        return True