示例#1
0
文件: fishdist.py 项目: prisae/gempy
 def plot_vMF_2D(self, poles=True):
     mean = self.xyz_to_spherical_coordinates(self.mu)
     points_sph = self.pointssph
     fig, ax = mplstereonet.subplots(figsize=(5, 5))
     if poles is True:
         for point in points_sph:
             ax.pole(point[0] - 90,
                     point[1],
                     color='k',
                     linewidth=1,
                     marker='v',
                     markersize=6,
                     label=('samples'))
         ax.pole(mean[0] - 90,
                 mean[1],
                 color='r',
                 markersize=6,
                 label='mean')
     ax.grid()
     ax.density_contourf(points_sph[:, 0] - 90,
                         points_sph[:, 1],
                         measurement='poles',
                         cmap='inferno',
                         alpha=0.7)
     ax.set_title('kappa = ' + str(self.kappa), y=1.2)
示例#2
0
def setup_axes(strike,dip,friction,to_plot):

    # Make a figure with a single stereonet axes
    fig, ax = st.subplots(ncols=3,projection='equal_angle_stereonet')

    for a in range(3):
        ax[a].plane(strike,dip,'k--',alpha=0.5,lw=5)#,label='SF')
#   planar failure
    plt.sca(ax[0])
    ax[0].set_title('planar\n')
    ax[0].grid(True)
    planar_friction(friction,to_plot)
    planar_daylight(strike,dip,to_plot)    
#    wedge failure    
    plt.sca(ax[1])
    ax[1].set_title('wedge\n')
    ax[1].grid(True)
    wedge_friction(friction,to_plot)
    wedge_daylight(strike,dip,to_plot)    
#    toppling failure
    plt.sca(ax[2])
    ax[2].set_title('toppling\n')
    ax[2].grid(True)
    toppling_friction(strike,dip,friction,to_plot)
    toppling_slipLimits(strike,dip,to_plot)
    
    return fig,ax
def setup_figure():
    """Setup the figure and axes"""
    fig, axes = mplstereonet.subplots(ncols=2, figsize=(20,10))
    for ax in axes:
        # Make the grid lines solid.
        ax.grid(ls='-')
        # Make the longitude grids continue all the way to the poles
        ax.set_longitude_grid_ends(90)
    return fig, axes
def setup_figure():
    """Setup the figure and axes"""
    fig, axes = mplstereonet.subplots(ncols=2, figsize=(20, 10))
    for ax in axes:
        # Make the grid lines solid.
        ax.grid(ls='-')
        # Make the longitude grids continue all the way to the poles
        ax.set_longitude_grid_ends(90)
    return fig, axes
示例#5
0
def plot_stereonet(self, litho=None, planes=True, poles=True,
                   single_plots=False,
                   show_density=False):
    if mplstereonet_import is False:
        raise ImportError(
            'mplstereonet package is not installed. No stereographic projection available.')

    from collections import OrderedDict

    if litho is None:
        litho = self.model.orientations.df['surface'].unique()

    if single_plots is False:
        fig, ax = mplstereonet.subplots(figsize=(5, 5))
        df_sub2 = pn.DataFrame()
        for i in litho:
            df_sub2 = df_sub2.append(self.model.orientations.df[
                                         self.model.orientations.df[
                                             'surface'] == i])

    for formation in litho:
        if single_plots:
            fig = plt.figure(figsize=(5, 5))
            ax = fig.add_subplot(111, projection='stereonet')
            ax.set_title(formation, y=1.1)

        # if series_only:
        # df_sub = self.model.orientations.df[self.model.orientations.df['series'] == formation]
        # else:
        df_sub = self.model.orientations.df[
            self.model.orientations.df['surface'] == formation]

        if poles:
            ax.pole(df_sub['azimuth'] - 90, df_sub['dip'], marker='o',
                    markersize=7,
                    markerfacecolor=self._color_lot[formation],
                    markeredgewidth=1.1, markeredgecolor='gray',
                    label=formation + ': ' + 'pole point')
        if planes:
            ax.plane(df_sub['azimuth'] - 90, df_sub['dip'],
                     color=self._color_lot[formation],
                     linewidth=1.5, label=formation + ': ' + 'azimuth/dip')
        if show_density:
            if single_plots:
                ax.density_contourf(df_sub['azimuth'] - 90, df_sub['dip'],
                                    measurement='poles', cmap='viridis',
                                    alpha=.5)
            else:
                ax.density_contourf(df_sub2['azimuth'] - 90, df_sub2['dip'],
                                    measurement='poles', cmap='viridis',
                                    alpha=.5)

        fig.subplots_adjust(top=0.8)
        handles, labels = ax.get_legend_handles_labels()
        by_label = OrderedDict(zip(labels, handles))
        ax.legend(by_label.values(), by_label.keys(), bbox_to_anchor=(1.9, 1.1))
        ax.grid(True, color='black', alpha=0.25)
示例#6
0
    def plot_stereonet(self,
                       poles=True,
                       planes=False,
                       density=True,
                       samples=None):
        """
        Plots the orientations in a stereonet.
        Args:
            poles: If True, the pole points are plotted
            samples (np.ndarray): orientations in cartesian coordinates that should be plotted.

        Returns:

        """
        if samples is None:
            samples = self.samples_azdip
        else:
            if samples.ndim == 3:
                samples = self._cartesian2spherical(samples)
        fig, ax = mplstereonet.subplots(figsize=(5, 5))
        if poles is True:
            try:
                mean_sph = self._cartesian2spherical(self.mean)
                #ax.pole(mean_sph[0] - 90, mean_sph[1], color='#015482', markersize=10, label='mean',
                #markeredgewidth=1, markeredgecolor='black')
            except AttributeError:
                pass
            for point in samples:
                ax.pole(point[0] - 90,
                        point[1],
                        linewidth=1,
                        color='#015482',
                        markersize=4,
                        markeredgewidth=0.5,
                        markeredgecolor='black')
                if planes is True:
                    ax.plane(point[0] - 90,
                             point[1],
                             linewidth=2,
                             color='#015482',
                             markersize=4,
                             markeredgewidth=0.5,
                             markeredgecolor='black')

        ax._grid()
        if density:
            ax.density_contour(samples[:, 0] - 90,
                               samples[:, 1],
                               measurement='poles',
                               sigma=1,
                               method='exponential_kamb',
                               cmap='Blues_r')
        try:
            ax.set_title('kappa = ' + str(round(self.kappa)), y=1.2)
        except AttributeError:
            pass
def plotter(data):

    fig, ax = mplstereonet.subplots()
    strikes = data[:, 0]
    dips = data[:, 1]
    cax = ax.density_contourf(strikes, dips, measurement='poles', cmap='Reds')
    ax.pole(strikes, dips, c='k', markersize=1)
    ax.grid(True)
    fig.colorbar(cax)
    plt.show()
示例#8
0
def plotter(data):
    
    fig, ax = mplstereonet.subplots()
    strikes = data[:,0]
    dips = data[:,1]
    cax = ax.density_contourf(strikes, dips, measurement='poles', cmap='Reds')
    ax.pole(strikes, dips, c='k', markersize=1)
    ax.grid(True)
    fig.colorbar(cax)
    plt.show()
示例#9
0
def setup_axes(strike, dip, friction, failure='all', to_plot=True):

    if failure == 'all':

        fig, ax = st.subplots(ncols=3, projection='equal_angle_stereonet')

        for a in range(3):
            ax[a].plane(strike, dip, 'k--', alpha=0.5, lw=5)  #,label='SF')
    #   planar failure
        plt.sca(ax[0])
        ax[0].set_title('planar\n\n')
        ax[0].grid(True)
        planar_friction(friction, to_plot)
        planar_daylight(strike, dip, to_plot)
        #    wedge failure
        plt.sca(ax[1])
        ax[1].set_title('wedge\n\n')
        ax[1].grid(True)
        wedge_friction(friction, to_plot)
        wedge_daylight(strike, dip, to_plot)
        #    toppling failure
        plt.sca(ax[2])
        ax[2].set_title('toppling\n\n')
        ax[2].grid(True)
        toppling_friction(strike, dip, friction, to_plot)
        toppling_slipLimits(strike, dip, to_plot)

    else:
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='equal_angle_stereonet')
        ax.plane(strike, dip, 'k--', alpha=0.5, lw=5)

        if failure == 'planar':
            ax.set_title('planar\n\n')
            ax.grid(True)
            planar_friction(friction, to_plot)
            planar_daylight(strike, dip, to_plot)

        elif failure == 'wedge':
            ax.set_title('wedge\n\n')
            ax.grid(True)
            wedge_friction(friction, to_plot)
            wedge_daylight(strike, dip, to_plot)

        elif failure == 'toppling':
            ax.set_title('toppling\n\n')
            ax.grid(True)
            toppling_friction(strike, dip, friction, to_plot)
            toppling_slipLimits(strike, dip, to_plot)
        else:
            ax.grid(True)

        fig.tight_layout()

    return fig, ax
示例#10
0
    def __init__(self, canvas, iface, parent=None):
        super(GtStereo, self).__init__(parent)
        self.canvas = canvas
        self.iface = iface
        self.figure, self.ax = mplstereonet.subplots()
        self.ax.text(0.75,-0.04, "lower-hemisphere \"schmitt\" \n(equal area) projection.",transform = self.ax.transAxes, ha='left', va='center')
        self.canvas = FigureCanvas(self.figure)
        self.polesbutton = QtWidgets.QPushButton('Plot Poles')
        self.polesbutton.clicked.connect(self.plotpoles)
        self.circlebutton = QtWidgets.QPushButton('Fit Fold')
        self.circlebutton.clicked.connect(self.fitfold)
        self.densitybutton = QtWidgets.QPushButton('Plot Density')
        self.densitybutton.clicked.connect(self.plotdensity)
        self.resetbutton = QtWidgets.QPushButton('Clear Plot')
        self.resetbutton.clicked.connect(self.reset)

        self.toolbar = NavigationToolbar(self.canvas, self)
        self.vector_layer_combo_box = QgsMapLayerComboBox()
        self.vector_layer_combo_box.setCurrentIndex(-1)
        self.vector_layer_combo_box.setFilters(QgsMapLayerProxyModel.VectorLayer)
        self.dip_dir = QCheckBox("Dip Direction")
        self.dip_dir.setChecked(True)
        self.strike = QCheckBox("Strike")
        self.strike.stateChanged.connect(self.strikordirection)
        self.button_group = QButtonGroup()
        self.button_group.addButton(self.dip_dir)
        self.button_group.addButton(self.strike)
        self.selected_features = QCheckBox()
        self.strike_combo_box = QgsFieldComboBox()
        self.dip_combo_box = QgsFieldComboBox()
        top_form_layout = QtWidgets.QFormLayout()
        layout = QtWidgets.QVBoxLayout()
        self.direction_name = QLabel("Dip Direction") 
        top_form_layout.addRow("Layer:",self.vector_layer_combo_box)
        top_form_layout.addRow(self.direction_name,self.strike_combo_box)
        top_form_layout.addRow(self.strike,self.dip_dir)
        top_form_layout.addRow("Dip:",self.dip_combo_box)
        top_form_layout.addRow("Selected Features Only:",self.selected_features)
        self.vector_layer_combo_box.layerChanged.connect(self.strike_combo_box.setLayer)  # setLayer is a native slot function
        self.vector_layer_combo_box.layerChanged.connect(self.dip_combo_box.setLayer)  # setLayer is a native slot function
        self.vector_layer_combo_box.layerChanged.connect(self.layer_changed)
        layout.addLayout(top_form_layout)
        layout.addWidget(self.canvas)
        layout.addWidget(self.toolbar)
        #layout.addWidget(self.strike_combo)
        #layout.addWidget(self.dip_combo)
        bottom_form_layout = QtWidgets.QFormLayout()
        bottom_form_layout.addWidget(self.polesbutton)
        bottom_form_layout.addWidget(self.circlebutton)
        bottom_form_layout.addWidget(self.densitybutton)
        bottom_form_layout.addWidget(self.resetbutton)
        layout.addLayout(bottom_form_layout)
        self.setLayout(layout)
示例#11
0
def basic():
    """Set up a basic stereonet and plot the same data each time."""
    fig, ax = mplstereonet.subplots()

    strike, dip = 315, 30
    ax.plane(strike, dip, color='lightblue')
    ax.pole(strike, dip, color='green', markersize=15)
    ax.rake(strike, dip, 40, marker='*', markersize=20, color='green')

    # Make a bit of room for the title...
    fig.subplots_adjust(top=0.8)

    return ax
示例#12
0
def splotDirect(gvect):

    if gvect.isUpward:
        plunge, bearing = gvect.mirrorHoriz().pt
        symbol = "x"
    else:
        plunge, bearing = gvect.pt
        symbol = "o"

    fig, ax = ms.subplots()

    ax.line(plunge, bearing, marker=symbol)
    ax.grid()
    plt.show()
示例#13
0
def demo_wedge():
    #    slope face
    strike = 60
    dip = 55
    #    generalized friction angle of slip planes
    friction = 25

    fig, ax = st.subplots(ncols=4, projection='equal_angle_stereonet')
    plt.sca(ax[0])
    ax[0].grid(True)
    ax[0].plane(strike, dip, 'k--', alpha=0.5, lw=5)
    plt.title('Plot slope face\n')

    plt.sca(ax[1])
    ax[1].grid(True)
    ax[1].plane(strike, dip, 'k--', alpha=0.5, lw=5)
    env.wedge_daylight(strike, dip)
    env.wedge_friction(friction)
    plt.title('Plot\n daylight and friction\nenvelopes\n')

    jstr = np.random.randint(0, 361, 4)
    jdip = np.random.randint(0, 91, 4)

    plt.sca(ax[2])
    ax[2].grid(True)
    ax[2].plane(strike, dip, 'k--', alpha=0.5, lw=5)
    env.wedge_daylight(strike, dip)
    env.wedge_friction(friction)
    ax[2].plane(jstr, jdip, c='k')
    plt.title('Plot discontinuity\nplanes\n')

    plt.sca(ax[3])
    ax[3].grid(True)
    ax[3].plane(strike, dip, 'k--', alpha=0.5, lw=5)
    env.wedge_daylight(strike, dip)
    env.wedge_friction(friction)
    ax[3].plane(jstr, jdip, c='k')

    curax = ax[3]
    for j in range(len(jstr) - 1):
        for k in range(j + 1, len(jstr)):
            wl_plunge, wl_bearing = st.plane_intersection(
                jstr[j], jdip[j], jstr[k], jdip[k])
            curax.line(wl_plunge,
                       wl_bearing,
                       'b^',
                       label=str(j + 1) + 'x' + str(k + 1))
    plt.title('Plot plane intersections,\n evaluate results\n')
    fig.suptitle('Wedge failure')
示例#14
0
    def __init__(self, canvas, iface, parent=None):
        super(Window, self).__init__(parent)
        self.canvas = canvas
        self.iface = iface
        self.layer = self.iface.mapCanvas().currentLayer()
        fields = self.layer.pendingFields()
        #self.strike_combo = QtGui.QComboBox()
        #self.dip_combo = QtGui.QComboBox()

        #for f in fields:
        #    self.strike_combo.addItem(f.name())
        #    self.dip_combo.addItem(f.name())
            # a figure instance to plot on
        #self.figure = plt.figure()
        self.figure, self.ax = mplstereonet.subplots()
        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.polesbutton = QtGui.QPushButton('Plot Poles')
        self.polesbutton.clicked.connect(self.plotpoles)
        self.circlebutton = QtGui.QPushButton('Fit Fold')
        self.circlebutton.clicked.connect(self.fitfold)
        self.densitybutton = QtGui.QPushButton('Plot Density')
        self.densitybutton.clicked.connect(self.plotdensity)
        self.resetbutton = QtGui.QPushButton('Clear Plot')
        self.resetbutton.clicked.connect(self.reset)

        self.figure.canvas.mpl_connect('button_press_event',self.onclick)
        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        #layout.addWidget(self.strike_combo)
        #layout.addWidget(self.dip_combo)
        layout.addWidget(self.polesbutton)
        layout.addWidget(self.circlebutton)
        layout.addWidget(self.densitybutton)
        layout.addWidget(self.resetbutton)
        self.setLayout(layout)
示例#15
0
    def plot_stereonet(self, poles=True, samples=None):
        """

        Args:
            poles:

        Returns:

        """
        if samples is None:
            samples = self.samples_azdip
        else:
            if samples.ndim == 3:
                samples = self._cartesian2spherical(samples)
        fig, ax = mplstereonet.subplots(figsize=(5, 5))
        if poles is True:
            try:
                mean_sph = self._cartesian2spherical(self.mean)
                #ax.pole(mean_sph[0] - 90, mean_sph[1], color='#015482', markersize=10, label='mean',
                #markeredgewidth=1, markeredgecolor='black')
            except AttributeError:
                pass
            for point in samples:
                ax.pole(point[0] - 90,
                        point[1],
                        linewidth=1,
                        color='#015482',
                        markersize=4,
                        markeredgewidth=0.5,
                        markeredgecolor='black')

        ax.grid()
        ax.density_contour(samples[:, 0] - 90,
                           samples[:, 1],
                           measurement='poles',
                           sigma=1,
                           method='linear_kamb',
                           cmap='Blues_r')
        try:
            ax.set_title('kappa = ' + str(round(self.kappa)), y=1.2)
        except AttributeError:
            pass
示例#16
0
def demo_toppling():
    #    slope face
    strike = 60
    dip = 55
    #    generalized friction angle of slip planes
    friction = 25

    fig, ax = st.subplots(ncols=4, projection='equal_angle_stereonet')
    plt.sca(ax[0])
    ax[0].grid(True)
    ax[0].plane(strike, dip, 'k--', alpha=0.5, lw=5)
    plt.title('Plot slope face\n')

    plt.sca(ax[1])
    ax[1].grid(True)
    ax[1].plane(strike - strike, dip, 'k--', alpha=0.5, lw=5)
    ax[1].set_azimuth_ticks([])
    env.toppling_slipLimits(strike - strike, dip)
    env.toppling_friction(strike - strike, dip, friction)
    plt.title('Rotate, plot\n daylight and friction\nenvelopes\n')

    jstr = np.random.randint(0, 361, 4)  #np.random.random_integers(0,360,4)
    jdip = np.random.randint(0, 91, 4)

    plt.sca(ax[2])
    ax[2].grid(True)
    ax[2].plane(strike, dip, 'k--', alpha=0.5, lw=5)
    env.toppling_slipLimits(strike, dip)
    env.toppling_friction(strike, dip, friction)
    ax[2].plane(jstr, jdip, c='k')
    plt.title('Rotate back,\nplot discontinuity planes\n')

    plt.sca(ax[3])
    ax[3].grid(True)
    ax[3].plane(strike, dip, 'k--', alpha=0.5, lw=5)
    env.toppling_slipLimits(strike, dip)
    env.toppling_friction(strike, dip, friction)
    ax[3].plane(jstr, jdip, c='k')
    ax[3].pole(jstr, jdip)
    plt.title('Plot poles, evaluate results\n')
    fig.suptitle('Toppling failure')
示例#17
0
    def get_stereonets(self, filepath, savename, directory, show):
        dir = directory + '/%s' % (savename.strip('.yaml'))
        if not os.path.exists(dir):
            os.makedirs(dir)

        dir_seaborn = dir + '/Stereonet'
        if not os.path.exists(dir_seaborn):
            os.makedirs(dir_seaborn)

        if filepath.endswith('.yaml') == True:
            with open(filepath, 'r') as stream:
                data_file = yaml.load(stream)
                stream.close()
                data = data_file['data']
                # parameters = data_file['parameters']
        else:
            # parameters = open(filepath, "r").readlines()[:33]
            data = np.loadtxt(filepath, delimiter=',', skiprows=70)

        df = pd.DataFrame(data,
                          columns=[
                              "Epicentral_distance", "Depth", "Strike", "Dip",
                              "Rake", "Misfit_accepted", "Misfit_rejected",
                              "Acceptance", "Epi_reject", "depth_reject",
                              "Strike_reject", "Dip_reject", "Rake_reject"
                          ])
        fig, ax = mplstereonet.subplots()

        strikes = df[["Strike"]]
        dips = df[["Dip"]]

        cax = ax.density_contourf(strikes, dips, measurement='poles')

        ax.pole(strikes, dips)
        ax.grid(True)
        fig.colorbar(cax)

        plt.show()
        a = 1
示例#18
0
def demo_planar(strike=60,dip=55,friction=25,jstr=np.random.randint(0,361,4),jdip=np.random.randint(15,91,4)):
    
    fig, ax = st.subplots(ncols=4,projection='equal_angle_stereonet')
    plt.sca(ax[0])
    ax[0].grid(True)
    ax[0].plane(strike,dip,'k--',alpha=0.5,lw=5)
    plt.title('Plot slope face\n')
    
    plt.sca(ax[1])
    ax[1].grid(True)
    ax[1].plane(strike-strike,dip,'k--',alpha=0.5,lw=5)
    ax[1].set_azimuth_ticks([])
    env.planar_daylight(strike-strike,dip)
    env.planar_friction(friction)
    plt.title('Rotate, plot\n daylight and friction\nenvelopes\n')
    
#    if jstr==-1 or jdip==-1:
#        jstr=np.random.randint(0,361,4)
#        jdip=np.random.randint(0,91,4)
    
    plt.sca(ax[2])
    ax[2].grid(True)
    ax[2].plane(strike,dip,'k--',alpha=0.5,lw=5)
    env.planar_daylight(strike,dip)
    env.planar_friction(friction)
    ax[2].plane(jstr,jdip,c='k')
    plt.title('Rotate back,\nplot discontinuity planes\n')
    
    plt.sca(ax[3])
    ax[3].grid(True)
    ax[3].plane(strike,dip,'k--',alpha=0.5,lw=5)
    env.planar_daylight(strike,dip)
    env.planar_friction(friction)
    ax[3].plane(jstr,jdip,c='0.5')
    ax[3].pole(jstr,jdip,c='k')
    plt.title('Plot poles, evaluate results\n')
    fig.suptitle('Planar failure\n\n')
示例#19
0
""" 
Demonstrating more control on the parameters (e.g. friction angle and lateral 
limits) of the analysis and plotting style for planar sliding and toppling 
failure. Similar for wedge failure.
"""

import matplotlib.pyplot as plt
import mplstereonet
import mplstereonet.kinematic_analysis as kinematic

# Set up the analysis with friction angle and lateral limits
P2 = kinematic.PlanarSliding(strike=0, dip=80, fric_angle=40, latlim=30)
T2 = kinematic.FlexuralToppling(strike=0, dip=80, fric_angle=40, latlim=30)

# Start plotting
fig, (ax1, ax2) = mplstereonet.subplots(ncols=2, figsize=(12, 9))

# Customizing with the kwargs - example with planar sliding failure
P2.plot_kinematic(daylight_kws={
    'ec': 'b',
    'label': 'Daylight Envelope'
},
                  friction_kws={
                      'ec': 'green',
                      'label': 'Friction Cone (40$^\circ$)',
                      'ls': '-.'
                  },
                  lateral_kws={
                      'color': 'purple',
                      'label': 'Lateral Limits ($\pm30^\circ$)',
                      'ls': '--'
示例#20
0
文件: plot.py 项目: pjhaest/gempy
def plot_stereonet(geo_data,
                   litho=None,
                   series_only=False,
                   planes=True,
                   poles=True,
                   single_plots=False,
                   show_density=False,
                   legend=True):
    '''
    Plots an equal-area projection of the orientations dataframe using mplstereonet.
    Only works after assigning the series for the right color assignment.

    Args:
        geo_data (gempy.DataManagement.InputData): Input data of the model
        litho (list): selection of formation or series names. If None, all are plotted
        series_only (bool): to decide if the data is plotted per series or per formation
        planes (bool): plots azimuth and dip as great circles
        poles (bool): plots pole points (plane normal vectors) of azimuth and dip
        single_plots (bool): plots each formation in a single stereonet
        show_density (bool): shows density contour plot around the pole points
        legend (bool): shows legend

    Returns:
        None
    '''

    import warnings
    try:
        import mplstereonet
    except ImportError:
        warnings.warn(
            'mplstereonet package is not installed. No stereographic projection available.'
        )

    import matplotlib.pyplot as plt
    from gempy.plotting.colors import cmap
    from collections import OrderedDict
    import pandas as pn

    if litho is None:
        if series_only:
            litho = geo_data.orientations['series'].unique()
        else:
            litho = geo_data.orientations['formation'].unique()

    if single_plots is False:
        fig, ax = mplstereonet.subplots(figsize=(5, 5))
        df_sub2 = pn.DataFrame()
        for i in litho:
            if series_only:
                df_sub2 = df_sub2.append(geo_data.orientations[
                    geo_data.orientations['series'] == i])
            else:
                df_sub2 = df_sub2.append(geo_data.orientations[
                    geo_data.orientations['formation'] == i])

    for formation in litho:
        if single_plots:
            fig = plt.figure(figsize=(5, 5))
            ax = fig.add_subplot(111, projection='stereonet')
            ax.set_title(formation, y=1.1)

        if series_only:
            df_sub = geo_data.orientations[geo_data.orientations['series'] ==
                                           formation]
        else:
            df_sub = geo_data.orientations[geo_data.orientations['formation']
                                           == formation]

        if poles:
            ax.pole(df_sub['azimuth'] - 90,
                    df_sub['dip'],
                    marker='o',
                    markersize=7,
                    markerfacecolor=cmap(df_sub['formation_number'].values[0]),
                    markeredgewidth=1.1,
                    markeredgecolor='gray',
                    label=formation)  #+': '+'pole point')
        if planes:
            ax.plane(df_sub['azimuth'] - 90,
                     df_sub['dip'],
                     color=cmap(df_sub['formation_number'].values[0]),
                     linewidth=1.5,
                     label=formation)
        if show_density:
            if single_plots:
                ax.density_contourf(df_sub['azimuth'] - 90,
                                    df_sub['dip'],
                                    measurement='poles',
                                    cmap='viridis',
                                    alpha=.5)
            else:
                ax.density_contourf(df_sub2['azimuth'] - 90,
                                    df_sub2['dip'],
                                    measurement='poles',
                                    cmap='viridis',
                                    alpha=.5)

        fig.subplots_adjust(top=0.8)
        if legend:
            handles, labels = ax.get_legend_handles_labels()
            by_label = OrderedDict(zip(labels, handles))
            ax.legend(by_label.values(),
                      by_label.keys(),
                      bbox_to_anchor=(1.9, 1.1))
        ax.grid(True, color='black', alpha=0.25)
    return fig
"""
import matplotlib.pyplot as plt
import mplstereonet

import parse_angelier_data

def plot(ax, strike, dip, rake, **kwargs):
    ax.rake(strike, dip, rake, 'ko', markersize=2)
    ax.density_contour(strike, dip, rake, measurement='rakes', **kwargs)


# Load data from Angelier, 1979
strike, dip, rake = parse_angelier_data.load()

# Setup a subplot grid
fig, axes = mplstereonet.subplots(nrows=3, ncols=4)

# Hide azimuth tick labels
for ax in axes.flat:
    ax.set_azimuth_ticks([])

contours = [range(2, 18, 2), range(1,21,2), range(1,22,2)]

# "Standard" Kamb contouring with different confidence levels.
for sigma, ax, contour in zip([3, 2, 1], axes[:,0], contours):
    # We're reducing the gridsize to more closely match a traditional
    # hand-contouring grid, similar to Kamb's original work and Vollmer's
    # Figure 5. `gridsize=10` produces a 10x10 grid of density estimates.
    plot(ax, strike, dip, rake, method='kamb', sigma=sigma,
        levels=contour, gridsize=10)
示例#22
0
def plot(ax, strike, dip, rake, **kwargs):
    ax.rake(strike, dip, rake, 'ko', markersize=2)
    ax.density_contour(strike,
                       dip,
                       rake,
                       measurement='rakes',
                       linewidths=1,
                       cmap='jet',
                       **kwargs)


# Load data from Angelier, 1979
strike, dip, rake = parse_angelier_data.load()

# Setup a subplot grid
fig, axes = mplstereonet.subplots(nrows=3, ncols=4)

# Hide azimuth tick labels
for ax in axes.flat:
    ax.set_azimuth_ticks([])

contours = [range(2, 18, 2), range(1, 21, 2), range(1, 22, 2)]

# "Standard" Kamb contouring with different confidence levels.
for sigma, ax, contour in zip([3, 2, 1], axes[:, 0], contours):
    # We're reducing the gridsize to more closely match a traditional
    # hand-contouring grid, similar to Kamb's original work and Vollmer's
    # Figure 5. `gridsize=10` produces a 10x10 grid of density estimates.
    plot(ax,
         strike,
         dip,
示例#23
0
def splot(data, force=''):
    """
    Plot geological data with matplotlib and mplstereonet
    """
    def params_gvect(gvect, kwargs, force_emisphere):

        if force_emisphere == 'lower':
            default_marker = default_gvect_marker_downward_symbol
            if gvect.isUpward:
                plot_orien = gvect.opposite()
            else:
                plot_orien = gvect
        elif force_emisphere == 'upper':
            default_marker = default_gvect_marker_upward_symbol
            if gvect.isDownward:
                plot_orien = gvect.opposite()
            else:
                plot_orien = gvect
        elif not force_emisphere:
            plot_orien = gvect
            default_marker = default_gvect_marker_downward_symbol if not plot_orien.isUpward else default_gvect_marker_upward_symbol
        else:
            raise PlotException("Invalid force emisphere parameter")

        if plot_orien.isUpward:  # apparently mplstereonet does not handle negative plunges
            plot_orien = plot_orien.mirrorHoriz()

        bearing, plunge = plot_orien.d
        symbol = kwargs.get("m", default_marker)
        color = kwargs.get("c", default_gvect_marker_color)

        return plunge, bearing, symbol, color

    def params_gaxis(gaxis, kwargs, force_emisphere):

        if (not force_emisphere) or (force_emisphere == 'lower'):
            default_marker = default_gaxis_marker_downward_symbol
            if gaxis.isUpward:
                plot_gaxis = gaxis.opposite()
            else:
                plot_gaxis = gaxis
        elif force_emisphere == 'upper':
            default_marker = default_gaxis_marker_upward_symbol
            if gaxis.isDownward:
                plot_gaxis = gaxis.opposite()
            else:
                plot_gaxis = gaxis
        else:
            raise PlotException("Invalid force emisphere parameter")

        if plot_gaxis.isUpward:  # apparently mplstereonet does not handle negative plunges
            plot_gaxis = plot_gaxis.mirrorHoriz()

        bearing, plunge = plot_gaxis.d
        symbol = kwargs.get("m", default_marker)
        color = kwargs.get("c", default_gaxis_marker_color)

        return plunge, bearing, symbol, color

    def params_gplane(gplane, kwargs, force_emisphere):

        if (not force_emisphere) or (force_emisphere == 'lower'):
            default_line_style = default_gplane_downward_linestyle
            plot_gplane = gplane
        elif force_emisphere == 'upper':
            default_line_style = default_gplane_upward_linestyle
            plot_gplane = gplane.mirrorVertPPlane()
        else:
            raise PlotException("Invalid force emisphere parameter")

        strike, dip = plot_gplane.srda

        line_style = kwargs.get("m", default_line_style)
        color = kwargs.get("c", default_gplane_line_color)

        return strike, dip, line_style, color

    if not isinstance(data, list):
        data = [data]

    if force not in ('', 'upper', 'lower'):
        raise PlotException("Force parameter not isValid")

    fig, ax = ms.subplots()

    for rec in data:

        if isinstance(rec, tuple):
            if isinstance(rec[-1], str):
                params = rec[-1]
                objs = rec[:-1]
            else:
                params = None
                objs = rec
        else:
            objs = [rec]
            params = None

        if params:
            kwargs = string2dict(params)
        else:
            kwargs = dict()

        for obj in objs:
            if isDirect(obj):
                plunge, bearing, symbol, color = params_gvect(
                    obj, kwargs, force_emisphere=force)
                ax.line(plunge,
                        bearing,
                        marker=symbol,
                        markerfacecolor=color,
                        markeredgecolor=color)
            elif isAxis(obj):
                plunge, bearing, symbol, color = params_gaxis(
                    obj, kwargs, force_emisphere=force)
                ax.line(plunge,
                        bearing,
                        marker=symbol,
                        markerfacecolor=color,
                        markeredgecolor=color)
            elif isPlane(obj):
                strike, dip, linestyle, color = params_gplane(
                    obj, kwargs, force_emisphere=force)
                ax.plane(strike, dip, linestyle=linestyle, color=color)

    ax.grid()
    plt.show()
示例#24
0
def plot_bedding_stereonets_old(orientations,all_sorts):
    import mplstereonet
    import matplotlib.pyplot as plt
    
    groups=all_sorts['group'].unique()
    print("All observations n=",len(orientations))

    fig, ax = mplstereonet.subplots(figsize=(7,7))
    strikes = orientations["azimuth"].values -90
    dips = orientations["dip"].values
    cax = ax.density_contourf(strikes, dips, measurement='poles')
    ax.pole(strikes, dips, markersize=5, color='w')
    ax.grid(True)
    text = ax.text(2.2, 1.37, "All data", color='b')
    plt.show()

    for gp in groups:
        all_sorts2=all_sorts[all_sorts["group"]==gp]
        all_sorts2.set_index("code",  inplace = True)

        frames={}
        first=True
        for indx,as2 in all_sorts2.iterrows():
            orientations2=orientations[orientations["formation"]==indx]
            if(first):
                first=False
                all_orientations=orientations2.copy()
            else:
                all_orientations=pd.concat([all_orientations,orientations2],sort=False)

        if(len(all_orientations)>0):
            print("----------------------------------------------------------------------------------------------------------------------")
            print(gp,"observations n=",len(all_orientations))
            fig, ax = mplstereonet.subplots(figsize=(5,5))
            strikes = all_orientations["azimuth"].values -90
            dips = all_orientations["dip"].values
            cax = ax.density_contourf(strikes, dips, measurement='poles')
            ax.pole(strikes, dips, markersize=5, color='w')
            ax.grid(True)
            text = ax.text(2.2, 1.37,gp, color='b')
            plt.show()

    for gp in groups:
        all_sorts2=all_sorts[all_sorts["group"]==gp]
        all_sorts2.set_index("code",  inplace = True)

        print("----------------------------------------------------------------------------------------------------------------------")
        print(gp)
        #display(all_sorts2)
        ind=0

        for indx,as2 in all_sorts2.iterrows():
            ind2=int(fmod(ind,3))
            orientations2=orientations[orientations["formation"]==indx]
            print(indx,"observations n=",len(orientations2))
            #display(orientations2)
            if(len(orientations2)>0):
                if(ind2==0):
                    fig, ax = mplstereonet.subplots(1,3,figsize=(15,15))
                strikes = orientations2["azimuth"].values -90
                dips = orientations2["dip"].values

                cax = ax[ind2].density_contourf(strikes, dips, measurement='poles')
                ax[ind2].pole(strikes, dips, markersize=5, color='w')
                ax[ind2].grid(True)
                #fig.colorbar(cax)
                text = ax[ind2].text(2.2, 1.37, indx, color='b')
                
                # Fit a plane to the girdle of the distribution and display it.
                fit_strike, fit_dip = mplstereonet.fit_girdle(strikes, dips)
                print('strike/dip of girdle',fit_strike, '/', fit_dip)                
               
                if(ind2==2):
                    plt.show()

                ind=ind+1

        if(ind>0 and not ind2==2):
            plt.show()
示例#25
0
def plot_bedding_stereonets(orientations_clean,geology,c_l,display):
    import mplstereonet
    import matplotlib.pyplot as plt
    
    orientations = gpd.sjoin(orientations_clean, geology, how="left", op="within")
    
    groups=geology[c_l['g']].unique()
    codes=geology[c_l['c']].unique()
    print("All observations n=",len(orientations_clean))
    print('groups',groups,'\ncodes',codes)

    if(display):
        fig, ax = mplstereonet.subplots(figsize=(7,7))
    if(c_l['otype']=='dip direction'):
        strikes = orientations[c_l['dd']].values -90
    else:
        strikes = orientations[c_l['dd']].values
       
    dips = orientations[c_l['d']].values
    if(display):
        cax = ax.density_contourf(strikes, dips, measurement='poles')
        ax.pole(strikes, dips, markersize=5, color='w')
        ax.grid(True)
        text = ax.text(2.2, 1.37, "All data", color='b')
        plt.show()
    group_girdle={}

    for gp in groups:
        
        all_orientations=orientations[orientations[c_l['g']]==gp]
        if(len(all_orientations)==1):
            print("----------------------------------------------------------------------------------------------------------------------")
            print(gp,"observations has 1 observation")
            group_girdle[gp]=(-999,-999,1)
            
        elif(len(all_orientations)>0):
            print("----------------------------------------------------------------------------------------------------------------------")
            print(gp,"observations n=",len(all_orientations))
            if(display):
                fig, ax = mplstereonet.subplots(figsize=(5,5))
            if(c_l['otype']=='dip direction'):
                strikes = all_orientations[c_l['dd']].values -90
            else:
                strikes = all_orientations[c_l['dd']].values
               
            dips = all_orientations[c_l['d']].values
            if(display):
                cax = ax.density_contourf(strikes, dips, measurement='poles')
                ax.pole(strikes, dips, markersize=5, color='w')
                ax.grid(True)
                text = ax.text(2.2, 1.37,gp, color='b')
                plt.show()
            fit_strike, fit_dip = mplstereonet.fit_girdle(strikes, dips)
            (plunge,), (bearing,) = mplstereonet.pole2plunge_bearing(fit_strike, fit_dip)            
            group_girdle[gp]=(plunge, bearing,len(all_orientations))
            print('strike/dip of girdle',fit_strike, '/', fit_dip)                
        else:
            print("----------------------------------------------------------------------------------------------------------------------")
            print(gp,"observations has no observations")
            group_girdle[gp]=(-999,-999,0)

    if(False):
        for gp in groups:

            print("----------------------------------------------------------------------------------------------------------------------")
            print(gp)
            #display(all_sorts2)
            ind=0
            orientations2=orientations[orientations[c_l['g']]==gp]
    
            for code in codes:
                orientations3=orientations2[orientations2[c_l['c']]==code]
                ind2=int(fmod(ind,3))
                if(len(orientations3)>0):
                    print(code,"observations n=",len(orientations3))
                #display(orientations2)
                if(len(orientations3)>0):
                    if(ind2==0):
                        fig, ax = mplstereonet.subplots(1,3,figsize=(15,15))
                    if(c_l['otype']=='dip direction'):
                        strikes = orientations3[c_l['dd']].values -90
                    else:
                        strikes = orientations3[c_l['dd']].values
    
                    dips = orientations3[c_l['d']].values
    
                    cax = ax[ind2].density_contourf(strikes, dips, measurement='poles')
                    ax[ind2].pole(strikes, dips, markersize=5, color='w')
                    ax[ind2].grid(True)
                    #fig.colorbar(cax)
                    text = ax[ind2].text(2.2, 1.37, code, color='b')
                    
                    # Fit a plane to the girdle of the distribution and display it.
                    fit_strike, fit_dip = mplstereonet.fit_girdle(strikes, dips)
                    print('strike/dip of girdle',fit_strike, '/', fit_dip)                
                   
                    if(ind2==2):
                        plt.show()
    
                    ind=ind+1
                    
    
            if(ind>0 and not ind2==2):
                plt.show()
    return(group_girdle)
示例#26
0
"""
Example of how `ax.scatter` can be used to plot linear data on a stereonet
varying color and/or size by other variables.

This also serves as a general example of how to convert orientation data into
the coordinate system that the stereonet plot uses so that generic matplotlib
plotting methods may be used.
"""
import numpy as np
import matplotlib.pyplot as plt
import mplstereonet
np.random.seed(1)

strikes = np.arange(0, 360, 15)
dips = 45 * np.ones(strikes.size)
magnitude = np.random.random(strikes.size)

# Convert our strikes and dips to stereonet coordinates
lons, lats = mplstereonet.pole(strikes, dips)

# Now we'll plot our data and color by magnitude
fig, ax = mplstereonet.subplots()
sm = ax.scatter(lons, lats, c=magnitude, s=50, cmap='gist_earth')

ax.grid()
plt.show()


示例#27
0
    def plot_stereonet(self,
                       litho=None,
                       planes=True,
                       poles=True,
                       single_plots=False,
                       show_density=False):
        '''
        Plot an equal-area projection of the orientations dataframe using mplstereonet.

        Args:
            geo_model (gempy.DataManagement.InputData): Input data of the model
            series_only: To select whether a stereonet is plotted per series or per formation
            litho: selection of formation or series names, as list. If None, all are plotted
            planes: If True, azimuth and dip are plotted as great circles
            poles: If True, pole points (plane normal vectors) of azimuth and dip are plotted
            single_plots: If True, each formation is plotted in a single stereonet
            show_density: If True, density contour plot around the pole points is shown

        Returns:
            None
        '''

        try:
            import mplstereonet
        except ImportError:
            warnings.warn(
                'mplstereonet package is not installed. No stereographic projection available.'
            )

        from collections import OrderedDict
        import pandas as pn

        if litho is None:
            litho = self.model.orientations.df['surface'].unique()

        if single_plots is False:
            fig, ax = mplstereonet.subplots(figsize=(5, 5))
            df_sub2 = pn.DataFrame()
            for i in litho:
                df_sub2 = df_sub2.append(self.model.orientations.df[
                    self.model.orientations.df['surface'] == i])

        for formation in litho:
            if single_plots:
                fig = plt.figure(figsize=(5, 5))
                ax = fig.add_subplot(111, projection='stereonet')
                ax.set_title(formation, y=1.1)

            #if series_only:
            #df_sub = self.model.orientations.df[self.model.orientations.df['series'] == formation]
            #else:
            df_sub = self.model.orientations.df[
                self.model.orientations.df['surface'] == formation]

            if poles:
                ax.pole(df_sub['azimuth'] - 90,
                        df_sub['dip'],
                        marker='o',
                        markersize=7,
                        markerfacecolor=self._color_lot[formation],
                        markeredgewidth=1.1,
                        markeredgecolor='gray',
                        label=formation + ': ' + 'pole point')
            if planes:
                ax.plane(df_sub['azimuth'] - 90,
                         df_sub['dip'],
                         color=self._color_lot[formation],
                         linewidth=1.5,
                         label=formation + ': ' + 'azimuth/dip')
            if show_density:
                if single_plots:
                    ax.density_contourf(df_sub['azimuth'] - 90,
                                        df_sub['dip'],
                                        measurement='poles',
                                        cmap='viridis',
                                        alpha=.5)
                else:
                    ax.density_contourf(df_sub2['azimuth'] - 90,
                                        df_sub2['dip'],
                                        measurement='poles',
                                        cmap='viridis',
                                        alpha=.5)

            fig.subplots_adjust(top=0.8)
            handles, labels = ax.get_legend_handles_labels()
            by_label = OrderedDict(zip(labels, handles))
            ax.legend(by_label.values(),
                      by_label.keys(),
                      bbox_to_anchor=(1.9, 1.1))
            ax.grid(True, color='black', alpha=0.25)
示例#28
0
 def __init__(self, *args, **kwargs):
     _, self._ax = mplstereonet.subplots(*args, **kwargs)
     self._grid_state = False
     self._cax = None
     self._lgd = None
示例#29
0
 def __init__(self, *args, **kwargs):
     _, self._ax = mplstereonet.subplots(*args, **kwargs)
     self._grid_state = False
     self._cax = None
     self._lgd = None
示例#30
0
    coll = rose(azi, z=z, bidirectional=True)
    plt.xticks(np.radians(range(0, 360, 45)), 
               ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'])
    plt.colorbar(coll, orientation='horizontal')
    plt.rgrids()
    plt.xlabel('Dip (Degrees)')
    plt.title(arcpy.GetParameterAsText(5))
    pdf.savefig()    
    
# Stereo Plot
makeStereoplot = arcpy.GetParameterAsText(6) # Boolean for activating stereo plot
if str(makeStereoplot) == 'true':
    # from https://github.com/joferkington/mplstereonet    
    import mplstereonet
    plt.figure()
    fig, ax = mplstereonet.subplots()
    
    # data from output file; add 90 to adjust for strike
    strikes = [arr['trend'][i]+90 for i in range(len(arr['trend']))]
    dips = [abs(arr['plunge'][i]) for i in range(len(arr['plunge']))]
    
    cax = ax.density_contourf(strikes, dips, measurement='poles')
    
    ax.pole(strikes, dips)
    ax.grid(True)
    fig.colorbar(cax)
    plt.title(arcpy.GetParameterAsText(7))    
    pdf.savefig()   

# Save multipage pdf
if str(makeStereoplot) == 'true' or str(makeroseplot) == 'true':
示例#31
0
"""
Demonstrates plotting multiple linear features with a single ``ax.pole`` call.

The real purpose of this example is to serve as an implicit regression test for
some oddities in the way axes grid lines are handled in matplotlib and
mplstereonet.  A 2-vertex line can sometimes be confused for an axes grid line,
and they need different handling on a stereonet.
"""
import matplotlib.pyplot as plt
import mplstereonet

fig, ax = mplstereonet.subplots(figsize=(7, 7))
strike = [200, 250]
dip = [50, 60]
ax.pole(strike, dip, 'go', markersize=10)
ax.grid()
plt.show()
示例#32
-1
 def contourPlot(self):
     fig, ax = mplstereonet.subplots()
     strikes = list()
     dips = list()
     layers = self.iface.legendInterface().layers()
     for layer in layers:
         if layer.type() == QgsMapLayer.VectorLayer:
             iter = layer.selectedFeatures()
             strikeExists = layer.fieldNameIndex('strike')
             ddrExists = layer.fieldNameIndex('ddr')
             dipExists = layer.fieldNameIndex('dip')
             for feature in iter:
                 if strikeExists != -1 and dipExists != -1:
                     strikes.append(feature['strike'])
                     dips.append(feature['dip'])
                 elif ddrExists != -1 and dipExists != -1:
                     strikes.append(feature['ddr'] - 90)
                     dips.append(feature['dip'])
         else:
             continue
     cax = ax.density_contourf(strikes,
                               dips,
                               measurement='poles',
                               cmap=cm.coolwarm)
     ax.pole(strikes, dips, 'k+', markersize=7)
     ax.grid(True)
     #        fig.colorbar(cax)
     plt.show()