a
    Sic                    @   sX  d Z ddlmZ ddlZddlZddlZddlZddlZddl	Z
ddl	mZmZmZmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddl m!Z" ddl#m$Z% ddl&m'Z( ddlm)Z) ddl*m+Z+m,Z, ddl&m-Z- ddl.m/Z/ d	d
l0m1Z1 d	dl0m2Z2 d	dl0m3Z3 ej4e5dgdgdgdG dd de)Z6dddZ7dS )aR  
axes3d.py, original mplot3d version by John Porter
Created: 23 Sep 2005

Parts fixed by Reinier Heeres <reinier@heeres.eu>
Minor additions by Ben Axelrod <baxelrod@coroware.com>
Significant updates and revisions by Ben Root <ben.v.root@gmail.com>

Module containing Axes3D, an object which can plot 3D objects on a
2D matplotlib figure.
    )defaultdictN)_apicbook
_docstring_preprocess_data)Axes)_axis_method_wrapper_process_plot_format)Bbox)Triangulation   )art3d)proj3d)axis3dZxlim3dZylim3dZzlim3dxlimylimzlimc                       s  e Zd ZdZdZdZe ej	d< e
dZdddd	dd
dddd fddZdd Zdd Zdd Zdd Zdd Zdd ZeddZeddZe
jddd d!ed"d# Ze
jdd$d d!ed%d# Ze
jddd d!ed&d# Zdd'd(Zdd)d*Zdd+d,Zd fd.d/	Zd0d1d2d3Z dd4d5Z!e"j# fd6d7Z$d8d9 Z%d:d; Z&edd<Z'edd=Z(d>d? Z)ddddd@dAdBZ*ddDdEZ+ddFdGZ,ddHdIZ-dJdK Z.e
/ddLddddMdNdOZ0e1jj2Z3e1jj4Z5e0Z6dPdQ Z7dRdS Z8dTdU Z9eddVZ:eddWZ;ed$dWZ<eddWZ=e>dXj?g d\e;_e<_e=_eddYZ@eddZZAedd[ZBedd\ZCedd]ZDedd^d_d`idaZEeddbZFeFjreF jeGHdc7  _ddde ZIddfdgZJddhdiZKdjdk ZLdldm ZMddodpZNdqdr ZOdsdt ZPdudv ZQdwdx ZR fdydzZSd{d| ZTd}d~ ZUdd ZVdd ZWdd ZXdd ZYdd ZZdddZ[dd Z\dd Z]dd Z^e
_ddddddZ`d fdd	Zadd Zbdd Zcdd ZddddZed fdd	ZfefZgejfZhdd fdd
ZieiZjdddddddZkdd ZldddZmdd ZnddddddddZodddZpdddZqdddZrd ddZset d-dddd fdd
ZueuZvet d-dddd fdd
Zwdd Zxet ddd fddÄ
ZyeyZzet ddd fddń
Z{d fddǄ	Z|etg dȢdɍd fdd̄	Z}e}Z~et d fdd΄	Zet dddфZd fddԄ	Zet d0ddd-dלddلZeZdddddڜdd܄Zetg dݢdɍdddZdd-d fddZet dddd	dddddZeZ  ZS (  Axes3Dz
    3D Axes object.
    3dxyzr   z3.6N   ir   perspT)elevazimrollsharez	proj_type
box_aspectcomputed_zorderfocal_lengthc                   s  |du rg d}|| _ || _|| _| ||
 |	| _t | _t | _t | _	t | _
| | j| j | j || _|dur| jd | | d| _|dd}t j||g|R d|d| t   |   d| _d| _|   | jjjd	| j | jjjd
| j | jjjd| j |   | j !d | j"# $ddg}|d |d  \| _%| _&| j'dd (d |rt)j*dddd |+|  dS )a  
        Parameters
        ----------
        fig : Figure
            The parent figure.
        rect : tuple (left, bottom, width, height), default: None.
            The ``(left, bottom, width, height)`` axes position.
        elev : float, default: 30
            The elevation angle in degrees rotates the camera above and below
            the x-y plane, with a positive angle corresponding to a location
            above the plane.
        azim : float, default: -60
            The azimuthal angle in degrees rotates the camera about the z axis,
            with a positive angle corresponding to a right-handed rotation. In
            other words, a positive azimuth rotates the camera about the origin
            from its location along the +x axis towards the +y axis.
        roll : float, default: 0
            The roll angle in degrees rotates the camera about the viewing
            axis. A positive angle spins the camera clockwise, causing the
            scene to rotate counter-clockwise.
        sharez : Axes3D, optional
            Other Axes to share z-limits with.
        proj_type : {'persp', 'ortho'}
            The projection type, default 'persp'.
        box_aspect : 3-tuple of floats, default: None
            Changes the physical dimensions of the Axes3D, such that the ratio
            of the axis lengths in display units is x:y:z.
            If None, defaults to 4:4:3
        computed_zorder : bool, default: True
            If True, the draw order is computed based on the average position
            of the `.Artist`\s along the view direction.
            Set to False if you want to manually control the order in which
            Artists are drawn on top of each other using their *zorder*
            attribute. This can be used for fine-tuning if the automatic order
            does not produce the desired result. Note however, that a manual
            zorder will only be correct for a limited view angle. If the figure
            is rotated by the user, it will look wrong from certain angles.
        auto_add_to_figure : bool, default: False
            Prior to Matplotlib 3.4 Axes3D would add themselves
            to their host Figure on init.  Other Axes class do not
            do this.

            This behavior is deprecated in 3.4, the default is
            changed to False in 3.6.  The keyword will be undocumented
            and a non-False value will be an error in 3.7.
        focal_length : float, default: None
            For a projection type of 'persp', the focal length of the virtual
            camera. Must be > 0. If None, defaults to 1.
            For a projection type of 'ortho', must be set to either None
            or infinity (numpy.inf). If None, defaults to infinity.
            The focal length can be computed from a desired Field Of View via
            the equation: focal_length = 1/tan(FOV/2)

        **kwargs
            Other optional keyword arguments:

            %(Axes3D:kwdoc)s
        N)        r$         ?r%   r   datalimauto_add_to_figureFT)frameonr!   motion_notify_eventbutton_press_eventbutton_release_eventr   r   r   )r   r   r   z3.4z3.7aP  Axes3D(fig) adding itself to the figure is deprecated since %(since)s. Pass the keyword argument auto_add_to_figure=False and use fig.add_axes(ax) to suppress this warning. The default value of auto_add_to_figure is changed to False in mpl3.6 and True values will no longer work %(removal)s.  This is consistent with other Axes classes.)removalmessage),initial_aziminitial_elevinitial_rollset_proj_typer"   r
   unit
xy_viewLim
zz_viewLim
xy_dataLim
zz_dataLim	view_init_sharez_shared_axesjoin_adjustablepopsuper__init__set_axis_offset_axis_onM	fmt_zdata
mouse_initfigurecanvas	callbacks_connect_picklable_on_move_button_press_button_releaseset_top_viewpatchset_linewidthtransLimitsinverted	transform	_pseudo_w	_pseudo_hspinesset_visibler   warn_deprecatedadd_axes)selffigrectr   r   r   r   r    r!   r"   r#   argskwargsr'   Zpseudo_bbox	__class__ W/var/www/html/django/DPS/env/lib/python3.9/site-packages/mpl_toolkits/mplot3d/axes3d.pyr?   8   sd    @







	zAxes3D.__init__c                 C   s   d| _ d| _d S )NFT	_axis3donstalerX   r_   r_   r`   r@      s    zAxes3D.set_axis_offc                 C   s   d| _ d| _d S )NTra   rd   r_   r_   r`   rA      s    zAxes3D.set_axis_onc                 C   s   | j |S )zs
        For artists in an Axes, if the zaxis has units support,
        convert *z* using zaxis unit type
        )zaxisconvert_units)rX   r   r_   r_   r`   convert_zunits   s    zAxes3D.convert_zunitsc                 C   sN   d| j  }d| j  }d| j  }d| j  }| |f| j_| |f| j_d| _d S )Ngffffff?g?T)_distviewLim	intervalx	intervalyrc   )rX   ZxdwlZxdwZydwlZydwr_   r_   r`   rL      s    



zAxes3D.set_top_viewc                 C   s(   t | | _t | | _t | | _dS )z5Init 3D axes; overrides creation of regular X/Y axes.N)r   XAxisxaxisYAxisyaxisZZAxisre   rd   r_   r_   r`   
_init_axis   s    zAxes3D._init_axisc                 C   s   | j S )z0Return the ``ZAxis`` (`~.axis3d.Axis`) instance.re   rd   r_   r_   r`   	get_zaxis   s    zAxes3D.get_zaxisre   get_gridlinesget_ticklinesz3.1rm   z3.8)alternativer-   c                 C   s   | j S N)rm   rd   r_   r_   r`   <lambda>       zAxes3D.<lambda>ro   c                 C   s   | j S rv   )ro   rd   r_   r_   r`   rw      rx   c                 C   s   | j S rv   rq   rd   r_   r_   r`   rw      rx   c              
   C   s\   |p
|   \}}}}}}|||f|||f|||f|||f|||f|||f|||f|||fgS rv   )
get_w_lims)rX   valsminxmaxxminymaxyminzmaxzr_   r_   r`   	unit_cube   s    zAxes3D.unit_cubec                 C   s(   |d u r| j }| |}t||}|S rv   )rB   r   r   Zproj_points)rX   rz   rB   ZxyzsZtcuber_   r_   r`   
tunit_cube   s
    
zAxes3D.tunit_cubec                 C   s   |  ||}|d |d f|d |d f|d |d f|d |d f|d |d f|d |d f|d |d f|d |d f|d |d f|d |d f|d |d f|d |d fg}|S )	Nr   r                     )r   )rX   rz   rB   tcedgesr_   r_   r`   tunit_edges   s    zAxes3D.tunit_edgesFc                    s6  t jd|d t jd|||d || _|dv r2|dkrDg d}n4|dkrVd	d
g}n"|dkrhd	dg}n|dkrxd
dg}t| j | j	 | j
 g}tj|d
d}tj|d
d}t|| }	| j||	k d	 }
|	| j |
 }t| j| j| jfD ]:\}}||v r||| || d  || || d   qdS )a}  
        Set the aspect ratios.

        Parameters
        ----------
        aspect : {'auto', 'equal', 'equalxy', 'equalxz', 'equalyz'}
            Possible values:

            =========   ==================================================
            value       description
            =========   ==================================================
            'auto'      automatic; fill the position rectangle with data.
            'equal'     adapt all the axes to have equal aspect ratios.
            'equalxy'   adapt the x and y axes to have equal aspect ratios.
            'equalxz'   adapt the x and z axes to have equal aspect ratios.
            'equalyz'   adapt the y and z axes to have equal aspect ratios.
            =========   ==================================================

        adjustable : None
            Currently ignored by Axes3D

            If not *None*, this defines which parameter will be adjusted to
            meet the required aspect. See `.set_adjustable` for further
            details.

        anchor : None or str or 2-tuple of float, optional
            If not *None*, this defines where the Axes will be drawn if there
            is extra space due to aspect constraints. The most common way to
            to specify the anchor are abbreviations of cardinal directions:

            =====   =====================
            value   description
            =====   =====================
            'C'     centered
            'SW'    lower left corner
            'S'     middle of bottom edge
            'SE'    lower right corner
            etc.
            =====   =====================

            See `~.Axes.set_anchor` for further details.

        share : bool, default: False
            If ``True``, apply the settings to all shared Axes.

        See Also
        --------
        mpl_toolkits.mplot3d.axes3d.Axes3D.set_box_aspect
        )autoequalequalxyequalyzequalxzaspectr   )r   
adjustableanchorshare)r   r   r   r   r   r   r   r   r   r   r   r   r   r   axis       @N)r   check_in_listr>   
set_aspect_aspectnparrayrm   get_view_intervalro   re   meanptpmax_box_aspect	enumerate
set_xlim3d
set_ylim3d
set_zlim3d)rX   r   r   r   r   Z
ax_indicesZview_intervalsr   r   deltascaledeltasiset_limr]   r_   r`   r     s>    2



zAxes3D.set_aspectr   )zoomc                C   st   |dkrt d| d|du r0tjdtd}ntj|td}tjd|d |d	| tj| 9 }|| _d
| _	dS )a  
        Set the Axes box aspect.

        The box aspect is the ratio of height to width in display
        units for each face of the box when viewed perpendicular to
        that face.  This is not to be confused with the data aspect
        (which for Axes3D is always 'auto').  The default ratios are
        4:4:3 (x:y:z).

        To simulate having equal aspect in data space, set the box
        aspect to match your data range in each dimension.

        *zoom* controls the overall size of the Axes3D in the figure.

        Parameters
        ----------
        aspect : 3-tuple of floats or None
            Changes the physical dimensions of the Axes3D, such that the ratio
            of the axis lengths in display units is x:y:z.
            If None, defaults to (4,4,3).

        zoom : float, default: 1
            Control overall size of the Axes3D in the figure. Must be > 0.
        r   zArgument zoom = z must be > 0N)r   r   r   dtype)r   r   gIr|E?T)

ValueErrorr   asarrayfloatr   check_shapelinalgnormr   rc   )rX   r   r   r_   r_   r`   set_box_aspect`  s    zAxes3D.set_box_aspectc                 C   sp   |d u r| j dd}|  j}tj |}|j|j }d}|	 }|
|||}| ||  |d d S )NT)originalr   active)get_position
get_figuretransSubfiguremtransformsr
   r3   transformedheightwidthfrozenshrunk_to_aspect_set_positionanchored
get_anchor)rX   positiontransbb
fig_aspectr!   pbpb1r_   r_   r`   apply_aspect  s    
zAxes3D.apply_aspectc           	         s:  |   sd S |   | j| d| _|  }| |r@|| |nd  |  | _dd | j	D }| j
rtdd | j D d }| }}t|dd dd	D ]:}t|tjr||_|d7 }qt|tjr||_|d7 }qn|D ]}|  q| jr*| j D ]}|| q| j D ]}|| qt | d S )
NFc                 s   s,   | ]$}t |tjtjfr| r|V  qd S rv   )
isinstancemcoll
CollectionmpatchesPatchget_visible).0artistr_   r_   r`   	<genexpr>  s   zAxes3D.draw.<locals>.<genexpr>c                 s   s   | ]}|  V  qd S rv   )
get_zorder)r   r   r_   r_   r`   r     s   r   c                 S   s   |   S rv   )do_3d_projection)r   r_   r_   r`   rw     rx   zAxes3D.draw.<locals>.<lambda>T)keyreverse)r   _unstale_viewLimrM   draw_frameonget_axes_locatorr   get_projrB   	_childrenr"   r   	_axis_mapvaluessortedr   r   r   zorderr   r   r   rb   Z	draw_paner>   )	rX   rendererlocatorZcollections_and_patchesZzorder_offsetZcollection_zorderZpatch_zorderr   r   r]   r_   r`   r     sH    



zAxes3D.drawc                 C   sh   |   }| || j}|d d |d d k}|d d |d d k}|d d |d d k}|||fS )Nr   r   r   r   )ry   r   rB   )rX   rz   r   ZxhighZyhighZzhighr_   r_   r`   get_axis_position  s    zAxes3D.get_axis_positionc                 K   s   d S rv   r_   )rX   xysr\   r_   r_   r`   update_datalim  s    zAxes3D.update_datalim_get_autoscale_on_set_autoscale_onc                 C   s*   |dkrt d|| _| d d| _dS )a  
        Set padding of Z data limits prior to autoscaling.

        *m* times the data interval will be added to each end of that interval
        before it is used in autoscaling.  If *m* is negative, this will clip
        the data range instead of expanding it.

        For example, if your data is in the range [0, 2], a margin of 0.1 will
        result in a range [-0.2, 2.2]; a margin of -0.1 will result in a range
        of [0.2, 1.8].

        Parameters
        ----------
        m : float greater than -0.5
        g      z margin must be greater than -0.5r   TN)r   _zmargin_request_autoscale_viewrc   )rX   mr_   r_   r`   set_zmargin  s
    
zAxes3D.set_zmargin)r   r   r   tightc                G   s  |r&|dus|dus|dur&t dnBt|dkrD|d  } }}n$t|dkr\|\}}}n|rht d|du r|du r|du r|durtd|d	 | j| j| jfS |dur| | |dur| | |dur| 	| | j
||du|du|dud
 dS )z
        Set or retrieve autoscaling margins.

        See `.Axes.margins` for full documentation.  Because this function
        applies to 3D Axes, it also takes a *z* argument, and returns
        ``(xmargin, ymargin, zmargin)``.
        NzECannot pass both positional and keyword arguments for x, y, and/or z.r   r   r   zYMust pass a single positional argument for all margins, or one for each margin (x, y, z).Tzignoring tight=z in get mode)r   scalexscaleyscalez)	TypeErrorlenr   warn_external_xmargin_ymarginr   set_xmarginset_ymarginr   autoscale_view)rX   r   r   r   r   marginsr_   r_   r`   r     s,    



zAxes3D.marginsbothc                 C   s   |du rd}d}d}nl|dv r6|  t| |  }nd}|dv rZ| t| |  }nd}|dv r~| t| |  }nd}|r| jd|d |r| jd	|d |r| jd
|d dS )a  
        Convenience method for simple axis view autoscaling.

        See `.Axes.autoscale` for full documentation.  Because this function
        applies to 3D Axes, *axis* can also be set to 'z', and setting *axis*
        to 'both' autoscales all three axes.
        NT)r   r   F)r   r   r   r   r   )r   r   r   )set_autoscalex_onboolget_autoscalex_onset_autoscaley_onget_autoscaley_onset_autoscalez_onget_autoscalez_onr   )rX   enabler   r   r   r   r   r_   r_   r`   	autoscale  s,    


zAxes3D.autoscalec                 C   s   t |t |kr<| jt t |t |g|  n | j||  | j||  |d urt| j||  | 	  d S rv   )
r   shaper6   update_from_data_xycolumn_stackravelupdate_from_data_xupdate_from_data_yr7   r   )rX   XYZhad_datar_   r_   r`   auto_scale_xyz;  s    zAxes3D.auto_scale_xyzc                 C   s  |du rL| j }|sZ| jD ]0}t|tjr.d}qt|tjtjfrd} qZqnt	| }| _ |r| 
 r| jd   | jj\}}| j }	|	||\}}| jdkr|| | j }
||
8 }||
7 }|s|	||\}}| || |rr|  rr| jd   | jj\}}| j }|||\}}| jdkrP|| | j }
||
8 }||
7 }|sf|||\}}| || |r|  r| jd   | jj\}}| j }|||\}}| jdkr|| | j }
||
8 }||
7 }|s|||\}}| || dS )z
        Autoscale the view limits using the data limits.

        See `.Axes.autoscale_view` for full documentation.  Because this
        function applies to 3D Axes, it also takes a *scalez* argument.
        NTFr   r   r   r   )_tightr   r   mimage	AxesImagemlinesLine2Dr   r   r   r   r:   cleanr6   rj   rm   get_major_locatornonsingularr   view_limits
set_xboundr  rk   ro   r   
set_yboundr  r7   re   r   
set_zbound)rX   r   r   r   r   r  r   x0x1Zxlocatorr   y0y1Zylocatorz0z1Zzlocatorr_   r_   r`   r   I  s\    





zAxes3D.autoscale_viewc                 C   s4   |   \}}|  \}}|  \}}||||||fS )zGet 3D world limits.)
get_xlim3d
get_ylim3d
get_zlim3d)rX   r{   r|   r}   r~   r   r   r_   r_   r`   ry     s    zAxes3D.get_w_limsemit)zminzmaxc                C   sf   |du rt |r|\}}|dur6|dur2td|}|durR|durNtd|}| jj||||dS )zW
        Set 3D z limits.

        See `.Axes.set_ylim` for full documentation
        Nz$Cannot pass both 'bottom' and 'zmin'z!Cannot pass both 'top' and 'zmax'r&  r   )r   iterabler   re   _set_lim)rX   bottomtopr&  r   r'  r(  r_   r_   r`   set_zlim  s    zAxes3D.set_zlimc                 C   s   t | jjS rv   )tupler4   rj   rd   r_   r_   r`   get_xlim  s    zAxes3D.get_xlimc                 C   s   t | jjS rv   )r/  r4   rk   rd   r_   r_   r`   get_ylim  s    zAxes3D.get_ylimc                 C   s   t | jjS )zGet 3D z limits.)r/  r5   rj   rd   r_   r_   r`   get_zlim  s    zAxes3D.get_zlim	get_scale_set_axes_scalea  
        Set the {}-axis scale.

        Parameters
        ----------
        value : {{"linear"}}
            The axis scale type to apply.  3D axes currently only support
            linear scales; other scales yield nonsensical results.

        **kwargs
            Keyword arguments are nominally forwarded to the scale class, but
            none of them is applicable for linear scales.
        get_ticklocs	set_ticksget_majorticklabelsget_minorticklabelsget_ticklabels_set_ticklabelszAxis.set_tickszAxes3D.set_zticks)doc_sub	axis_datez

        Notes
        -----
        This function is merely provided for completeness, but 3D axes do not
        support dates for ticks, and so this may not work as expected.
        c                 O   s   dS )z:Currently not implemented for 3D axes, and returns *None*.Nr_   )rX   r[   r\   r_   r_   r`   clabel  s    zAxes3D.clabelc                 C   sl   d| _ |du r| j| _n|| _|du r0| j| _n|| _|du rH| j| _n|| _tjt	dddd|d| _
dS )a  
        Set the elevation and azimuth of the axes in degrees (not radians).

        This can be used to rotate the axes programmatically.

        To look normal to the primary planes, the following elevation and
        azimuth angles can be used. A roll angle of 0, 90, 180, or 270 deg
        will rotate these views while keeping the axes at right angles.

        ==========   ====  ====
        view plane   elev  azim
        ==========   ====  ====
        XY           90    -90
        XZ           0     -90
        YZ           0     0
        -XY          -90   90
        -XZ          0     90
        -YZ          0     180
        ==========   ====  ====

        Parameters
        ----------
        elev : float, default: None
            The elevation angle in degrees rotates the camera above the plane
            pierced by the vertical axis, with a positive angle corresponding
            to a location above that plane. For example, with the default
            vertical axis of 'z', the elevation defines the angle of the camera
            location above the x-y plane.
            If None, then the initial value as specified in the `Axes3D`
            constructor is used.
        azim : float, default: None
            The azimuthal angle in degrees rotates the camera about the
            vertical axis, with a positive angle corresponding to a
            right-handed rotation. For example, with the default vertical axis
            of 'z', a positive azimuth rotates the camera about the origin from
            its location along the +x axis towards the +y axis.
            If None, then the initial value as specified in the `Axes3D`
            constructor is used.
        roll : float, default: None
            The roll angle in degrees rotates the camera about the viewing
            axis. A positive angle spins the camera clockwise, causing the
            scene to rotate counter-clockwise.
            If None, then the initial value as specified in the `Axes3D`
            constructor is used.
        vertical_axis : {"z", "x", "y"}, default: "z"
            The axis to align vertically. *azim* rotates about this axis.
        
   Nr   r   r   r   )vertical_axis)rh   r0   r   r/   r   r1   r   r   check_getitemdict_vertical_axis)rX   r   r   r   r?  r_   r_   r`   r8     s    1


zAxes3D.view_initc                 C   sv   t jddg|d |dkrH|du r(d}n|dkr@td| d|| _n*|dtjfvrjtd| d	| tj| _dS )
a  
        Set the projection type.

        Parameters
        ----------
        proj_type : {'persp', 'ortho'}
            The projection type.
        focal_length : float, default: None
            For a projection type of 'persp', the focal length of the virtual
            camera. Must be > 0. If None, defaults to 1.
            The focal length can be computed from a desired Field Of View via
            the equation: focal_length = 1/tan(FOV/2)
        r   ortho)r    Nr   r   zfocal_length = z must be greater than 0z must be None for proj_type = )r   r   r   _focal_lengthr   inf)rX   r    r#   r_   r_   r`   r2   &  s    
zAxes3D.set_proj_typec                 C   s   t || jd S )z1Roll arrays to match the different vertical axis.r   )r   r   rB  )rX   arrr_   r_   r`   _roll_to_verticalB  s    zAxes3D._roll_to_verticalc                 C   s  |  | j}tjg |  |  |  R d|i}d| }tt	
| j}tt	
| j}tt	
| j}t|t| }t|t| }t|}	|  |||	g}
|| j|
  }|| _|| | _| jtj| j | _td}t|dtj krdnd|| j< | jtjkrHt||||}t| j | j}n:|| j|
 | j  }t||||}t| j | j| j}t||}t||}|S )z?Create the projection matrix from the current viewing position.Z	pb_aspect      ?r   r   )rG  r   r   Zworld_transformationr#  r$  r%  r   deg2radr   _norm_angler   r   r   cossinrh   eyeZvvecr   r   zerosabspirB  rD  rE  Zview_transformationZortho_transformationZpersp_transformationdot)rX   r!   ZworldMRZelev_radZazim_radZroll_radp0p1p2psrN  VZviewMZprojMZ	eye_focalM0rB   r_   r_   r`   r   F  sH    


"
zAxes3D.get_projr   c                 C   s*   d| _ t| | _t| | _dS )aa  
        Set the mouse buttons for 3D rotation and zooming.

        Parameters
        ----------
        rotate_btn : int or list of int, default: 1
            The mouse button or buttons to use for 3D rotation of the axes.
        zoom_btn : int or list of int, default: 3
            The mouse button or buttons to use to zoom the 3D axes.
        N)button_pressedr   
atleast_1dtolist_rotate_btn	_zoom_btn)rX   
rotate_btnzoom_btnr_   r_   r`   rD     s    zAxes3D.mouse_initc                 C   s   | j g g d dS )z2Disable mouse buttons for 3D rotation and zooming.)r_  r`  N)rD   rd   r_   r_   r`   disable_mouse_rotation  s    zAxes3D.disable_mouse_rotationc                 C   s   dS )z
        Return whether this Axes supports the zoom box button functionality.

        Axes3D objects do not use the zoom box button.
        Fr_   rd   r_   r_   r`   can_zoom  s    zAxes3D.can_zoomc                 C   s   dS )z
        Return whether this Axes supports the pan/zoom button functionality.

        Axes3d objects do not use the pan/zoom button.
        Fr_   rd   r_   r_   r`   can_pan  s    zAxes3D.can_panc                 C   s   t jtjj|d | jdur.|| jur.td| jd | | || _|j	j
| j	_
|j	j| j	_| \}}| j||d| d |j	j| j	_dS )z
        Share the z-axis with *other*.

        This is equivalent to passing ``sharex=other`` when constructing the
        Axes, and cannot be used if the z-axis is already being shared with
        another Axes.
        )otherNzz-axis is already sharedr   Fr)  )r   check_isinstancemaxes_base	_AxesBaser9   r   r:   r;   re   majorminorr2  r.  r  _scale)rX   rd  r!  r"  r_   r_   r`   r     s    zAxes3D.sharezc                    s>   t    | jtjkr$tjd | _nd| _| tjd  d S )Nzaxes.zmarginr$   zaxes3d.grid)	r>   clearrD  r   rE  mplrcParamsr   gridrd   r]   r_   r`   rl    s
    
zAxes3D.clearc                 C   sT   |j | krP|j| _|j|j | _| _t| jj	d}|rP|
 d u rP| jj	j  d S Ntoolbar)inaxesbuttonrZ  xdataydatasxsygetattrrE   rF   
_nav_stackrq  push_currentrX   eventrq  r_   r_   r`   rJ     s    
zAxes3D._button_pressc                 C   s*   d | _ t| jjd}|r&| jjj  d S rp  )rZ  rx  rE   rF   rq  rz  r{  r_   r_   r`   rK     s    zAxes3D._button_releasec                 C   s"   |   |  |  | j| j| jfS rv   )r0  r1  r2  r   r   r   rd   r_   r_   r`   	_get_view  s    zAxes3D._get_viewc                 C   s6   |\}}}}}}| j |||d || _|| _|| _d S )Nr   )setr   r   r   )rX   viewr   r   r   r   r   r   r_   r_   r`   	_set_view  s
    zAxes3D._set_viewc              	   C   s@   z|  |W S  ttfy:   | j j}||}| Y S 0 dS )z
        Return *z* string formatted.  This function will use the
        :attr:`fmt_zdata` attribute if it is callable, else will fall
        back on the zaxis major formatter
        N)rC   AttributeErrorr   re   get_major_formatterformat_data_short)rX   r   funcvalr_   r_   r`   format_zdata  s    zAxes3D.format_zdatac                    s"  | j du rdS | j| jv rdt| j}t| j}t| j}d|dd|dd|dddd	S t	| 
  fd
dd\}}|\}}	}
|\}}}t|  |	 }t|  | }|| }|| |
 || |  }t || j \}}}| |}| |}| |}d|||f S )z
        Given the 2D view coordinates attempt to guess a 3D coordinate.
        Looks for the nearest edge to the point and then assumes that
        the point is at the same z location as the nearest point on the edge.
        N z
elevation=z.0fu   °, azimuth=u	   °, roll=   °-u   −c                    s   t | d | d  fS )Nr   r   )r   Z_line2d_seg_dist)edgexdydr_   r`   rw     s   z%Axes3D.format_coord.<locals>.<lambda>)r   zx=%s, y=%s, z=%s)rB   rZ  r]  r   rK  r   r   r   replaceminr   r   hypotr   Zinv_transformformat_xdataformat_ydatar  )rX   r  r  Z	norm_elevZ	norm_azimZ	norm_rollrT  rU  r  r  r!  r  r   r"  d0d1dtr   r   r   xsyszsr_   r  r`   format_coord  s6    







zAxes3D.format_coordc                 C   s  | j s
dS | jdu rdS |j|j }}|du r2dS || j || j  }}| j}| j}|| | _| _| j | jv r"|dkr|dkrdS t	
| j}||  d t	| || d t	|  }	||  d t	| || d t	|  }
| j|	 | _| j|
 | _|   d| _| jj  n| j dkrZ|dkrF|dkrFdS |  \}}}}}}d|| |  }d|| |  }t	
| j}t	
| j}|| |t	| t	| |t	|   }|| | t	| |t	| t	|   }|| | t	|  }| || ||  | || ||  | || ||  |   | jj  n| j | jv r |  \}}}}}}d|| |  }|| | }|| | }|| | }| || ||  | || ||  | || ||  |   | jj  dS )z
        Mouse moving.

        By default, button-1 rotates and button-3 zooms; these buttons can be
        modified via `mouse_init`.
        Nr      Tr   r   )rZ  rB   rt  ru  rv  rw  rR   rS   r]  r   rJ  r   rL  rM  r   r   r   rc   rE   rF   	draw_idlery   r   r   r   r^  )rX   r|  r   r   dxdywhr   ZdelevZdazimr{   r|   r}   r~   r   r   r   r   dxxZdyyZdzzdfdzr_   r_   r`   rI     sb    
...0zAxes3D._on_movec                 K   s&   |dur|| j _| j j||fi |S )zI
        Set zlabel.  See doc for `.set_ylabel` for description.
        N)re   labelpadset_label_text)rX   Zzlabelfontdictr  r\   r_   r_   r`   
set_zlabeli  s    zAxes3D.set_zlabelc                 C   s   | j  }| S )z.
        Get the z-label text string.
        )re   	get_labelget_text)rX   labelr_   r_   r`   
get_zlabelq  s    
zAxes3D.get_zlabelc                 C   s   | j S )z)Get whether the 3D axes panels are drawn.)r   rd   r_   r_   r`   get_frame_onz  s    zAxes3D.get_frame_onc                 C   s   t || _d| _dS )zs
        Set whether the 3D axes panels are drawn.

        Parameters
        ----------
        b : bool
        TN)r   r   rc   )rX   br_   r_   r`   set_frame_on~  s    
zAxes3D.set_frame_onz3.5r  visiblec                 K   s   t |rd}|| _d| _dS )z
        Set / unset 3D grid.

        .. note::

            Currently, this function does not behave the same as
            `.axes.Axes.grid`, but it is intended to eventually support that
            behavior.
        TN)r   Z
_draw_gridrc   )rX   r  r\   r_   r_   r`   ro    s    zAxes3D.gridc                    s   t jg d|d |dv r.t j|fi | |dv rt|}|dd |dd |dd |d	d | jjf i | dS )
ax  
        Convenience method for changing the appearance of ticks and
        tick labels.

        See `.Axes.tick_params` for full documentation.  Because this function
        applies to 3D Axes, *axis* can also be set to 'z', and setting *axis*
        to 'both' autoscales all three axes.

        Also, because of how Axes3D objects are drawn very differently
        from regular 2D axes, some of these settings may have
        ambiguous meaning.  For simplicity, the 'z' axis will
        accept settings as if it was like the 'y' axis.

        .. note::
           Axes3D currently ignores some of these settings.
        )r   r   r   r   r   )r   r   r   r   r-  Nr,  labeltoplabelbottom)r   r   r>   tick_paramsrA  r=   re   set_tick_params)rX   r   r\   Zzkwr]   r_   r`   r    s    zAxes3D.tick_paramsc                 C   s    |   \}}| j||dd dS )z$
        Invert the z-axis.
        Nr   )r2  r.  rX   r,  r-  r_   r_   r`   invert_zaxis  s    zAxes3D.invert_zaxisc                 C   s   |   \}}||k S )z9
        Returns True if the z-axis is inverted.
        r2  r  r_   r_   r`   zaxis_inverted  s    zAxes3D.zaxis_invertedc                 C   s(   |   \}}||k r||fS ||fS dS )zP
        Return the lower and upper z-axis bounds, in increasing order.
        Nr  r  r_   r_   r`   
get_zbound  s    zAxes3D.get_zboundc                 C   sd   |du rt |r|\}}|  \}}|du r2|}|du r>|}| jt||ft|  ddd dS )z
        Set the lower and upper numerical bounds of the z-axis.

        This method will honor axes inversion regardless of parameter order.
        It will not change the autoscaling setting (`.get_autoscalez_on()`).
        N)r   r  )r   r*  r  r.  r   r   r  )rX   lowerupper	old_lower	old_upperr_   r_   r`   r    s    
zAxes3D.set_zboundc                    s*   t  j|||fi |}t||| |S )z
        Add text to the plot. kwargs will be passed on to Axes.text,
        except for the *zdir* keyword, which sets the direction to be
        used as the z direction.
        )r>   textr   Ztext_2d_to_3d)rX   r   r   r   szdirr\   r  r]   r_   r`   r    s    zAxes3D.textr  c          
         s   |   }|r4t|d ts4|^}}d|v r@tdn|dd}t|t|}t j	||g|R i |}|D ]}	t
j|	||d qrt
||||\}}}| |||| |S )a0  
        Plot 2D or 3D data.

        Parameters
        ----------
        xs : 1D array-like
            x coordinates of vertices.
        ys : 1D array-like
            y coordinates of vertices.
        zs : float or 1D array-like
            z coordinates of vertices; either one for all points or one for
            each point.
        zdir : {'x', 'y', 'z'}, default: 'z'
            When plotting 2D data, the direction to use as z ('x', 'y' or 'z').
        **kwargs
            Other arguments are forwarded to `matplotlib.axes.Axes.plot`.
        r   r  z+plot() for multiple values for argument 'z'r  r  )has_datar   strr   r=   r   broadcast_tor  r>   plotr   line_2d_to_3djuggle_axesr  )
rX   r  r  r  r[   r\   r  r  linesliner]   r_   r`   r    s    
zAxes3D.plot)r   vminvmaxlightsourcec          !         s2  |   }	|jdkrtdt|}t|||\}}}|j\}
}d|v pPd|v }d|v p`d|v }|rr|rrtd|dd|dd|dd	}|dd	}t	j
d
 r|}n| }|rttt|
| dttt|| dd|v r|d}n4|dd}|du r"| j }tt|}d}|dd}|d|du }|du rdtdg }|
d  dkr|d  dkr|du rtjfdd|||fD dd}nttd|
d |
d g }ttd|d |d g }g }t|dd |dd D ]\t|dd |dd D ]Z\  fdd|||fD }t|j}|| |dur8||    q8qt|tjrt| r$g }g }t||D ]F\}}t|t|jdd  }t |r|| || q|}|dur$|}t!j"|fi |}|durp|rZ| #|| $||}|%| |&| n|rt|tjr|d j'dd} ntdd |D } |(|  |dus|dur|)|| |dur|*| n*|r| #|| $||}n|}|%| | +| | ,||||	 |S )a.	  
        Create a surface plot.

        By default it will be colored in shades of a solid color, but it also
        supports colormapping by supplying the *cmap* argument.

        .. note::

           The *rcount* and *ccount* kwargs, which both default to 50,
           determine the maximum number of samples used in each direction.  If
           the input data is larger, it will be downsampled (by slicing) to
           these numbers of points.

        .. note::

           To maximize rendering speed consider setting *rstride* and *cstride*
           to divisors of the number of rows minus 1 and columns minus 1
           respectively. For example, given 51 rows rstride can be any of the
           divisors of 50.

           Similarly, a setting of *rstride* and *cstride* equal to 1 (or
           *rcount* and *ccount* equal the number of rows and columns) can use
           the optimized path.

        Parameters
        ----------
        X, Y, Z : 2D arrays
            Data values.

        rcount, ccount : int
            Maximum number of samples used in each direction.  If the input
            data is larger, it will be downsampled (by slicing) to these
            numbers of points.  Defaults to 50.

        rstride, cstride : int
            Downsampling stride in each direction.  These arguments are
            mutually exclusive with *rcount* and *ccount*.  If only one of
            *rstride* or *cstride* is set, the other defaults to 10.

            'classic' mode uses a default of ``rstride = cstride = 10`` instead
            of the new default of ``rcount = ccount = 50``.

        color : color-like
            Color of the surface patches.

        cmap : Colormap
            Colormap of the surface patches.

        facecolors : array-like of colors.
            Colors of each individual patch.

        norm : Normalize
            Normalization for the colormap.

        vmin, vmax : float
            Bounds for the normalization.

        shade : bool, default: True
            Whether to shade the facecolors.  Shading is always disabled when
            *cmap* is specified.

        lightsource : `~matplotlib.colors.LightSource`
            The lightsource to use when *shade* is True.

        **kwargs
            Other arguments are forwarded to `.Poly3DCollection`.
        r   !Argument Z must be 2-dimensional.rstridecstridercountccount.Cannot specify both stride and count argumentsr>  2   _internal.classic_moder   
facecolorscolorNcmapshadezshade cannot be None.r   c                    s   g | ]}t | qS r_   )r   _array_patch_perimetersr   a)r  r  r_   r`   
<listcomp>  s   z'Axes3D.plot_surface.<locals>.<listcomp>rI  r   c              	      s.   g | ]&}t |d   d  f qS )r   )r   _array_perimeterr  )cscs_nextrsrs_nextr_   r`   r    s   ).r   c                 S   s    g | ]}|d d df   qS Nr   )r   )r   rW  r_   r_   r`   r    rx   )-r  ndimr   r   _to_unmasked_float_arrayr   broadcast_arraysr  r=   rm  rn  intr   ceil
_get_linesget_next_colorr   mcolorsto_rgbagetstacklistrangezipTappendr   ndarrayisnanany	itertoolszip_longestr   r   Poly3DCollection_shade_colors_generate_normalsset_facecolorsset_edgecolorsr   	set_arrayset_climset_normadd_collectionr  )!rX   r  r  r  r   r  r  r  r\   r  rowscols
has_stride	has_countr  r  Zcompute_stridesZfcolorsr  r  r  colsetpolysZrow_indscol_indsrW  Z	new_polysZ
new_colsetpcolZnew_polypolycavg_zr_   )r  r  r  r  r  r  r`   plot_surface  s    F







""










zAxes3D.plot_surfacec           
      C   s:  t |tjr||jd }d|d d| d   }}}|d|ddf |d|ddf  }|d|ddf |d|ddf  }ntt|df}tt|df}t|D ]\}}	t|	}d|d d| d   }}}|	|ddf |	|ddf  ||ddf< |	|ddf |	|ddf  ||ddf< qt||S )a  
        Compute the normals of a list of polygons.

        Normals point towards the viewer for a face with its vertices in
        counterclockwise order, following the right hand rule.

        Uses three points equally spaced around the polygon.
        This normal of course might not make sense for polygons with more than
        three points not lying in a plane, but it's a plausible and fast
        approximation.

        Parameters
        ----------
        polygons : list of (M_i, 3) array-like, or (..., M, 3) array-like
            A sequence of polygons to compute normals for, which can have
            varying numbers of vertices. If the polygons all have the same
            number of vertices and array is passed, then the operation will
            be vectorized.

        Returns
        -------
        normals : (..., 3) array
            A normal vector estimated for the polygon.
        r   r   r   .N)r   r   r  r  emptyr   r   cross)
rX   polygonsni1i2Zi3v1v2Zpoly_irW  r_   r_   r`   r    s    
$&,.zAxes3D._generate_normalsc           	         s   |du rt jddd}tjdd, |tjj|ddd	 |j }W d   n1 sT0    Y  t| }| rt 	d
d t 	ddj
 fdd}d|| < t |}|dddf }||ddtjf | }||dddf< nt| }|S )z
        Shade *color* using normal vectors given by *normals*.
        *color* can also be an array of the same length as *normals*.
        N   g-x3@)azdegaltdegignore)invalidr   T)r   keepdimsrI  333333?c                    s    | S rv   r_   )r   Zin_normZout_normr_   r`   r   #  s    z"Axes3D._shade_colors.<locals>.normr   r   )r  LightSourcer   errstater   r   	directionr  r  	Normalizeinverseto_rgba_arraynewaxis
asanyarraycopy)	rX   r  normalsr  r  maskr   alphacolorsr_   r  r`   r    s$    "

zAxes3D._shade_colorsc                    s  |   }jdkrtdt \ j\}}d|v pFd|v }d|v pVd|v }	|rh|	rhtd|dd}
|dd}|dd	}|dd	}tjd
 r|	r|rt	t
t|| dnd}
|rt	t
t|| dnd}nJ|s2|rt	t
t|| dnd}
|r.t	t
t|| dnd}t tt  |
rttd||
}|dkr|d |d kr||d g7 }ng }|rttd||}|dkr|d |d kr||d g7 }ng }|
dkr|dkrtdjdkrg }g } fdd|D }fdd|D }fdd|D }fdd|D }fdd|D }fdd|D }dd t|||D dd t|||D  }tj|fi |}| | |  | |S )a  
        Plot a 3D wireframe.

        .. note::

           The *rcount* and *ccount* kwargs, which both default to 50,
           determine the maximum number of samples used in each direction.  If
           the input data is larger, it will be downsampled (by slicing) to
           these numbers of points.

        Parameters
        ----------
        X, Y, Z : 2D arrays
            Data values.

        rcount, ccount : int
            Maximum number of samples used in each direction.  If the input
            data is larger, it will be downsampled (by slicing) to these
            numbers of points.  Setting a count to zero causes the data to be
            not sampled in the corresponding direction, producing a 3D line
            plot rather than a wireframe plot.  Defaults to 50.

        rstride, cstride : int
            Downsampling stride in each direction.  These arguments are
            mutually exclusive with *rcount* and *ccount*.  If only one of
            *rstride* or *cstride* is set, the other defaults to 1.  Setting a
            stride to zero causes the data to be not sampled in the
            corresponding direction, producing a 3D line plot rather than a
            wireframe plot.

            'classic' mode uses a default of ``rstride = cstride = 1`` instead
            of the new default of ``rcount = ccount = 50``.

        **kwargs
            Other arguments are forwarded to `.Line3DCollection`.
        r   r  r  r  r  r  r  r   r  r  r   rI  z*Either rstride or cstride must be non zeroc                    s   g | ]} | qS r_   r_   r   r   )r  r_   r`   r    rx   z)Axes3D.plot_wireframe.<locals>.<listcomp>c                    s   g | ]} | qS r_   r_   r+  )r  r_   r`   r    rx   c                    s   g | ]} | qS r_   r_   r+  )r  r_   r`   r    rx   c                    s   g | ]} | qS r_   r_   r+  )tXr_   r`   r    rx   c                    s   g | ]} | qS r_   r_   r+  )tYr_   r`   r    rx   c                    s   g | ]} | qS r_   r_   r+  )tZr_   r`   r    rx   c                 S   s"   g | ]\}}}t t|||qS r_   r  r  r   xlylzlr_   r_   r`   r    s   c                 S   s"   g | ]\}}}t t|||qS r_   r/  r0  r_   r_   r`   r    s   )r  r  r   r   r  r  r=   rm  rn  r  r   r  	transposer  r  sizer  r   Line3DCollectionr   r  )rX   r  r  r  r\   r  r  r  r  r  r  r  r  r  ZriiZciixlinesZylinesZzlinesZtxlinesZtylinesZtzlinesr  linecr_   )r  r  r  r,  r-  r.  r`   plot_wireframe4  sj    &


 """"


zAxes3D.plot_wireframe)r  r   r  r  r  c                O   s  |   }|du r| j }tt|}|dd}	|d|	du }
t	j
|i |\}}}z|d}W n ty   |^}}Y n0 t|}| }|j| }|j| }|| }tj|||fdd}tj|g|R i |}|	rD|dddddf jdd}|| |dus"|dur.||| |durr|| n.|
rd| |}| |||}n|}|| | | | |j|j|| |S )	aT  
        Plot a triangulated surface.

        The (optional) triangulation can be specified in one of two ways;
        either::

          plot_trisurf(triangulation, ...)

        where triangulation is a `~matplotlib.tri.Triangulation` object, or::

          plot_trisurf(X, Y, ...)
          plot_trisurf(X, Y, triangles, ...)
          plot_trisurf(X, Y, triangles=triangles, ...)

        in which case a Triangulation object will be created.  See
        `.Triangulation` for a explanation of these possibilities.

        The remaining arguments are::

          plot_trisurf(..., Z)

        where *Z* is the array of values to contour, one per point
        in the triangulation.

        Parameters
        ----------
        X, Y, Z : array-like
            Data values as 1D arrays.
        color
            Color of the surface patches.
        cmap
            A colormap for the surface patches.
        norm : Normalize
            An instance of Normalize to map values to colors.
        vmin, vmax : float, default: None
            Minimum and maximum value to map.
        shade : bool, default: True
            Whether to shade the facecolors.  Shading is always disabled when
            *cmap* is specified.
        lightsource : `~matplotlib.colors.LightSource`
            The lightsource to use when *shade* is True.
        **kwargs
            All other arguments are passed on to
            :class:`~mpl_toolkits.mplot3d.art3d.Poly3DCollection`

        Examples
        --------
        .. plot:: gallery/mplot3d/trisurf3d.py
        .. plot:: gallery/mplot3d/trisurf3d_2.py
        Nr  r  r  rI  r   r   r   )r  r  r  r   r   r  r  r  r=   r   get_from_args_and_kwargsKeyErrorr   get_masked_trianglesr   r   r  r   r  r   r  r  r  r  r  r  r   r  )rX   r  r   r  r  r  r[   r\   r  r  r  trir   	trianglesxtytZztvertsr
  r  r'  r  r_   r_   r`   plot_trisurf  sD    5








zAxes3D.plot_trisurfr   c              	   C   s  |j }|j}|d |d  d }t||D ]V\}}| }|sBq*t||| }	t||| }
| d }g }g }tt|	d | }|dkrt|	d dkr*d}nq*t|	d d |d  }t	t
t|d D ]Z}t
t|| }t
t|d | }||	d | |	d | |
d | |
d | g qt|}| |}| ||}| ||}tj|||d}|| | | q*|D ]}|  qdS )z4
        Extend a contour in 3D by creating
        r   r   r   r  
edgecolorsN)levelscollectionsr  	get_pathsr   Z_paths_to_3d_segmentsget_edgecolorroundr   r  r  r  r   r   r  r  r  set_sort_zposadd_collection3dremove)rX   csetstriderE  collsr  r   r8  pathsZtopvertsZbotvertsr  Z	polyvertsr'  Znstepsstepsizer   r  r  r*  Zcolors2Zpolycolr	  r_   r_   r`   _3d_extend_contour  sL    





zAxes3D._3d_extend_contourc                 C   sR   d| }|r|  || n4t|j|jD ]$\}}|d ur<|}tj|||d q(d S )Nr  r  )rR  r  rE  rF  r   line_collection_2d_to_3d)rX   rM  extend3drN  r  offsetr   r8  r_   r_   r`   add_contour_setB  s    zAxes3D.add_contour_setc                 C   s   | j |||d d S )Nr  rU  )_add_contourf_set)rX   rM  r  rU  r_   r_   r`   add_contourf_setM  s    zAxes3D.add_contourf_setc           	      C   s   d| }|j dd t|j d  }|jr\|j d t|j dd d  }t|d|}|jr|j d t|j dd d  }t||}t||jD ].\}}|dur|}t	j
|||d || q|S )z
        Returns
        -------
        levels : numpy.ndarray
            Levels at which the filled contours are added.
        r  NrI  r   r   r  r  )rE  r   diff_extend_mininsert_extend_maxr  r  rF  r   poly_collection_2d_to_3drJ  )	rX   rM  r  rU  Z	midpointsZ	min_level	max_levelr   r8  r_   r_   r`   rX  P  s    ""zAxes3D._add_contourf_set)rT  rN  r  rU  c                   sb   |   }
t||||\}}}t j|||g|R i |	}| ||||| | ||||
 |S )a9  
        Create a 3D contour plot.

        Parameters
        ----------
        X, Y, Z : array-like,
            Input data. See `.Axes.contour` for supported data shapes.
        extend3d : bool, default: False
            Whether to extend contour in 3D.
        stride : int
            Step size for extending contour.
        zdir : {'x', 'y', 'z'}, default: 'z'
            The direction to use.
        offset : float, optional
            If specified, plot a projection of the contour lines at this
            position in a plane normal to zdir.
        data : indexable object, optional
            DATA_PARAMETER_PLACEHOLDER

        *args, **kwargs
            Other arguments are forwarded to `matplotlib.axes.Axes.contour`.

        Returns
        -------
        matplotlib.contour.QuadContourSet
        )r  r   rotate_axesr>   contourrV  r  )rX   r  r  r  rT  rN  r  rU  r[   r\   r  jXjYjZrM  r]   r_   r`   ra  i  s    zAxes3D.contourc                   s   |   }tj|i |\}}}|j}	|j}
d|v r>|d}n|^}}t|	|
||\}}}t|||j|j	}t
 j||g|R i |}| ||||| | |	|
|| |S )a  
        Create a 3D contour plot.

        .. note::
            This method currently produces incorrect output due to a
            longstanding bug in 3D PolyCollection rendering.

        Parameters
        ----------
        X, Y, Z : array-like
            Input data. See `.Axes.tricontour` for supported data shapes.
        extend3d : bool, default: False
            Whether to extend contour in 3D.
        stride : int
            Step size for extending contour.
        zdir : {'x', 'y', 'z'}, default: 'z'
            The direction to use.
        offset : float, optional
            If specified, plot a projection of the contour lines at this
            position in a plane normal to zdir.
        data : indexable object, optional
            DATA_PARAMETER_PLACEHOLDER
        *args, **kwargs
            Other arguments are forwarded to `matplotlib.axes.Axes.tricontour`.

        Returns
        -------
        matplotlib.tri.tricontour.TriContourSet
        r  )r  r   r:  r   r   r=   r   r`  r>  r(  r>   
tricontourrV  r  )rX   rT  rN  r  rU  r[   r\   r  r=  r  r  r  rb  rc  rd  rM  r]   r_   r`   re    s"     zAxes3D.tricontourc                    s>   d|d|d|||i  fdddD }| j g ||R   d S )Nr   r   r   c                    s(   g | ] }t  | t  | fqS r_   r   nanminnanmax)r   dimZdim_valsr_   r`   r    s   z/Axes3D._auto_scale_contourf.<locals>.<listcomp>r   )r  )rX   r  r  r  r  rE  r  limitsr_   rj  r`   _auto_scale_contourf  s
    
zAxes3D._auto_scale_contourfrW  c                   sb   |   }t||||\}	}
}t j|	|
|g|R i |}| |||}| |||||| |S )a  
        Create a 3D filled contour plot.

        Parameters
        ----------
        X, Y, Z : array-like
            Input data. See `.Axes.contourf` for supported data shapes.
        zdir : {'x', 'y', 'z'}, default: 'z'
            The direction to use.
        offset : float, optional
            If specified, plot a projection of the contour lines at this
            position in a plane normal to zdir.
        data : indexable object, optional
            DATA_PARAMETER_PLACEHOLDER
        *args, **kwargs
            Other arguments are forwarded to `matplotlib.axes.Axes.contourf`.

        Returns
        -------
        matplotlib.contour.QuadContourSet
        )r  r   r`  r>   contourfrX  rl  )rX   r  r  r  r  rU  r[   r\   r  rb  rc  rd  rM  rE  r]   r_   r`   rm    s    zAxes3D.contourfc                   s   |   }tj|i |\}}}|j}|j}d|v r>|d}	n|^}	}t|||	|\}
}}t|
||j|j	}t
 j||g|R i |}| |||}| |||	||| |S )aV  
        Create a 3D filled contour plot.

        .. note::
            This method currently produces incorrect output due to a
            longstanding bug in 3D PolyCollection rendering.

        Parameters
        ----------
        X, Y, Z : array-like
            Input data. See `.Axes.tricontourf` for supported data shapes.
        zdir : {'x', 'y', 'z'}, default: 'z'
            The direction to use.
        offset : float, optional
            If specified, plot a projection of the contour lines at this
            position in a plane normal to zdir.
        data : indexable object, optional
            DATA_PARAMETER_PLACEHOLDER
        *args, **kwargs
            Other arguments are forwarded to
            `matplotlib.axes.Axes.tricontourf`.

        Returns
        -------
        matplotlib.tri.tricontour.TriContourSet
        r  )r  r   r:  r   r   r=   r   r`  r>  r(  r>   tricontourfrX  rl  )rX   r  rU  r[   r\   r  r=  r  r  r  rb  rc  rd  rM  rE  r]   r_   r`   rn    s"    zAxes3D.tricontourfc                    s   t |}|jrt |nd}t|tju rHtj|||d |	| nRt|tj
u rrtj|||d |	| n(t|tju rtj|||d |	| t |}|S )a  
        Add a 3D collection object to the plot.

        2D collection types are converted to a 3D version by
        modifying the object and adding z coordinate information.

        Supported are:

        - PolyCollection
        - LineCollection
        - PatchCollection
        r   r  )r   r[  r5  r  typer   PolyCollectionr   r^  rJ  LineCollectionrS  PatchCollectionpatch_collection_2d_to_3dr>   r   )rX   r	  r  r  ZzvalsZzsortval
collectionr]   r_   r`   rK  #  s    

zAxes3D.add_collection3d)	r  r  r  r  rD  c	facecolorr  r  )replace_names   c                    s   |   }
|}tjdd |||fD  \}}}tj|}t|||||\}}}}}t||rh| }t	 j
||g|R ||d|	}tj||||d | jdk r|jdkr| d | ||||
 |S )a  
        Create a scatter plot.

        Parameters
        ----------
        xs, ys : array-like
            The data positions.
        zs : float or array-like, default: 0
            The z-positions. Either an array of the same length as *xs* and
            *ys* or a single value to place all points in the same plane.
        zdir : {'x', 'y', 'z', '-x', '-y', '-z'}, default: 'z'
            The axis direction for the *zs*. This is useful when plotting 2D
            data on a 3D Axes. The data must be passed as *xs*, *ys*. Setting
            *zdir* to 'y' then plots the data to the x-z-plane.

            See also :doc:`/gallery/mplot3d/2dcollections3d`.

        s : float or array-like, default: 20
            The marker size in points**2. Either an array of the same length
            as *xs* and *ys* or a single value to make all markers the same
            size.
        c : color, sequence, or sequence of colors, optional
            The marker color. Possible values:

            - A single color format string.
            - A sequence of colors of length n.
            - A sequence of n numbers to be mapped to colors using *cmap* and
              *norm*.
            - A 2D array in which the rows are RGB or RGBA.

            For more details see the *c* argument of `~.axes.Axes.scatter`.
        depthshade : bool, default: True
            Whether to shade the scatter markers to give the appearance of
            depth. Each call to ``scatter()`` will perform its depthshading
            independently.
        data : indexable object, optional
            DATA_PARAMETER_PLACEHOLDER
        **kwargs
            All other arguments are passed on to `~.axes.Axes.scatter`.

        Returns
        -------
        paths : `~matplotlib.collections.PathCollection`
        c                 S   s"   g | ]}t t j|t jqS r_   )r   r	  mafillednan)r   tr_   r_   r`   r  z  rx   z"Axes3D.scatter.<locals>.<listcomp>)r  ru  )r  r  
depthshade皙?r   )r  r   r  ry  r	  r   delete_masked_pointsmay_share_memoryr&  r>   scatterr   rs  r   r5  r   r  )rX   r  r  r  r  r  ru  r}  r[   r\   r  Zzs_origpatchesr]   r_   r`   r  D  s"    2
"

zAxes3D.scatterc                    s   |   }t j||g|R i |}t|t|}g }	g }
t||D ]T\}}t|}|	|	 7 }	|
|gt| 7 }
t
||| d|v rF||d  qFt|	dkrt|	 \}}n
g g  }}t|||
|\}}}
| |||
| |S )a  
        Add 2D bar(s).

        Parameters
        ----------
        left : 1D array-like
            The x coordinates of the left sides of the bars.
        height : 1D array-like
            The height of the bars.
        zs : float or 1D array-like
            Z coordinate of bars; if a single value is specified, it will be
            used for all bars.
        zdir : {'x', 'y', 'z'}, default: 'z'
            When plotting 2D data, the direction to use as z ('x', 'y' or 'z').
        data : indexable object, optional
            DATA_PARAMETER_PLACEHOLDER
        **kwargs
            Other arguments are forwarded to `matplotlib.axes.Axes.bar`.

        Returns
        -------
        mpl_toolkits.mplot3d.art3d.Patch3DCollection
        r)  r   )r  r>   barr   r  r   r  r   Z_get_patch_vertsr\  Zpatch_2d_to_3d	set_alphar  r  )rX   leftr   r  r  r[   r\   r  r  rA  Zverts_zsr  r   vsr  r  r]   r_   r`   r    s$    

z
Axes3D.baraveragec                 O   s   |   }tt||||||\}}}}}}t|}t|| }t|}t|| }t|}t|| }tg d}t|j|j }d||fd||fd||ffD ]J\}}}|dtj	tj	f }|dtj	tj	f }|||d|f   |d|f< q|
d|jdd  }g }|du r0| j g}tt|}t|t|krn|D ]}||gd  qTn&|}t|t|k r|dt| 9 }|	r| |}| |||
}n|}tj|g|R ||d	|}| | | ||f||f||f| |S )
a  
        Generate a 3D barplot.

        This method creates three dimensional barplot where the width,
        depth, height, and color of the bars can all be uniquely set.

        Parameters
        ----------
        x, y, z : array-like
            The coordinates of the anchor point of the bars.

        dx, dy, dz : float or array-like
            The width, depth, and height of the bars, respectively.

        color : sequence of colors, optional
            The color of the bars can be specified globally or
            individually. This parameter can be:

            - A single color, to color all bars the same color.
            - An array of colors of length N bars, to color each bar
              independently.
            - An array of colors of length 6, to color the faces of the
              bars similarly.
            - An array of colors of length 6 * N bars, to color each face
              independently.

            When coloring the faces of the boxes specifically, this is
            the order of the coloring:

            1. -Z (bottom of box)
            2. +Z (top of box)
            3. -Y
            4. +Y
            5. -X
            6. +X

        zsort : str, optional
            The z-axis sorting scheme passed onto `~.art3d.Poly3DCollection`

        shade : bool, default: True
            When true, this shades the dark sides of the bars (relative
            to the plot's source of light).

        lightsource : `~matplotlib.colors.LightSource`
            The lightsource to use when *shade* is True.

        data : indexable object, optional
            DATA_PARAMETER_PLACEHOLDER

        **kwargs
            Any additional keyword arguments are passed onto
            `~.art3d.Poly3DCollection`.

        Returns
        -------
        collection : `~.art3d.Poly3DCollection`
            A collection of three dimensional polygons representing
            the bars.
        ))r   r   r   r   r   r   r   r   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r   r   )r  r  r  r  )r  r  r  r  )r  r  r  r  )r  r  r  r  r   r   r   .)rI  Nr   )zsortrv  )r  r   r  r[  r  r   r   r  r  r$  reshape_get_patches_for_fillr  r  r  r#  r   extendr  r  r   r  r   r  )rX   r   r   r   r  r  r  r  r  r  r  r[   r\   r  r{   r|   r}   r~   r   r   Zcuboidr  r   r  dpr  ru  r'  Zsfacecolorsr	  r_   r_   r`   bar3d  sT    ?


.&


zAxes3D.bar3dcenterc                    s<   t  j|f||d|}| j \}}| jd|  |S )N)r  locgq=
ףp?)r>   	set_titletitler   set_y)rX   r  r  r  r\   retr   r   r]   r_   r`   r  l	  s    zAxes3D.set_titler  tail)lengtharrow_length_ratiopivot	normalizec                   s  ddd}|   }d}	t||	k r6td|	t|f |d|	 }
dd |
D }tjg |
|R  }|d|	 }
||	d }|rttj|  fd	d|
D }
nd
d |
D }
tdd |
D rt	j
g g||	d R i |}| | |S tjd|gtd}|| }tjg d|d |dkr0||8 }n|dkrF||d 8 }t|
dd }t|
d|	 t}tjj|dd}|dk |  }|r|  |  d }n|  }t|dkr6|tj|| dd}||}|ddddf tj|| }|t|ddf}|dd}g ||}ng }t	j
|g||	d R i |}| | | |dddf |dddf |dddf | |S )a  
        ax.quiver(X, Y, Z, U, V, W, /, length=1, arrow_length_ratio=.3, pivot='tail', normalize=False, **kwargs)

        Plot a 3D field of arrows.

        The arguments could be array-like or scalars, so long as they
        they can be broadcast together. The arguments can also be
        masked arrays. If an element in any of argument is masked, then
        that corresponding quiver element will not be plotted.

        Parameters
        ----------
        X, Y, Z : array-like
            The x, y and z coordinates of the arrow locations (default is
            tail of arrow; see *pivot* kwarg).

        U, V, W : array-like
            The x, y and z components of the arrow vectors.

        length : float, default: 1
            The length of each quiver.

        arrow_length_ratio : float, default: 0.3
            The ratio of the arrow head with respect to the quiver.

        pivot : {'tail', 'middle', 'tip'}, default: 'tail'
            The part of the arrow that is at the grid point; the arrow
            rotates about this point, hence the name *pivot*.

        normalize : bool, default: False
            Whether all arrows are normalized to have the same length, or keep
            the lengths defined by *u*, *v*, and *w*.

        data : indexable object, optional
            DATA_PARAMETER_PLACEHOLDER

        **kwargs
            Any additional keyword arguments are delegated to
            :class:`~matplotlib.collections.LineCollection`
           c              
   S   sd  | d d df }| d d df }t jj| d d d df dd}t j|||dkt |d}t j| ||dkt |d}t|}t|}t	|}	t 
||d d|   || d|  ||	 g|| d|  ||d d|   | |	 g| |	 ||	 t ||gg}
|
 }|g dg df  d9  < t d	|
| }t d	|| }t j||gdd}|S )
Nr   r   r   r   )whereout)r   r   r   r   )r   r   r   r   rI  zij...,...j->...i)r   r   r   divide
zeros_like	ones_likemathradiansrL  rM  r   	full_liker&  einsumr  )UVWangler   r   r   Zx_py_praru  r  ZRposZRnegZ	Rpos_vecsZ	Rneg_vecs	head_dirsr_   r_   r`   calc_arrows	  s(     


(*z"Axes3D.quiver.<locals>.calc_arrowsr   z-Wrong number of arguments. Expected %d got %dNc                 S   s    g | ]}t |tjjr|jqS r_   )r   r   ry  MaskedArrayr(  r   kr_   r_   r`   r  	  s   z!Axes3D.quiver.<locals>.<listcomp>c                    s    g | ]}t jj| d  qS )r(  )r   ry  r   
compressedr  r  r_   r`   r  	  s   c                 S   s   g | ]}t |qS r_   )r   r	  r  r_   r_   r`   r  	  rx   c                 s   s   | ]}t |d kV  qdS )r   N)r   )r   vr_   r_   r`   r   	  rx   z Axes3D.quiver.<locals>.<genexpr>r$   r   )r  middletip)r  r  r  r   r   r   r   r   )rI  r   rI  )r  )r  r   r   r   r  	functoolsreduce
logical_orr  r   r6  r   r   r   r   r   r  astyper   r   r  multiplyouterswapaxesr  )rX   r  r  r  r  r[   r\   r  r  Zargi
input_argsmasksbcastr8  Zshaft_dtZarrow_dtZXYZr  r   Zshaftsr  headsr  r_   r  r`   quivers	  sb    .


 



" 
4zAxes3D.quiver)r  rD  r  r  c          2   	      s  t |dkrdd }ndd }||i |\}}jdkrDtdtjjtjd}	t|	d  |du r|t \}
}}n fd	d
|D \}
}}fdd}|du r| j	
 }||d}||d}| |
|| tjg dg dg dg dgtjd}tt}dd }|dD ]}|j|	\}}}t|}t|}t|}||j}|ddd }|D ]4}|D ]&}|||dg}t|}| r|| ||  t|dd |dd D ]\}}||||g} ||||g}!t| }"t|!}#|" r&|# s&||" |!|  n&|" sƈ|# r||# |!|  q||||d g}$||||g}%t|$}&|& rr||& |%|  qrqhqi }'| D ]\}(})|du r|)}*ng }*|)D ]}+|+dddf |+dddf |+dddf f},t|+j}-|
|, |-dddf< ||, |-dddf< ||, |-dddf< |*|- q||( }.||( }/|r| |*}0| |.|0|}.|/dur| |/|0|}/tj|*f|.|/d|}1| |1 |1|'|(< q|'S )a
  
        ax.voxels([x, y, z,] /, filled, facecolors=None, edgecolors=None, **kwargs)

        Plot a set of filled voxels

        All voxels are plotted as 1x1x1 cubes on the axis, with
        ``filled[0, 0, 0]`` placed with its lower corner at the origin.
        Occluded faces are not plotted.

        Parameters
        ----------
        filled : 3D np.array of bool
            A 3D array of values, with truthy values indicating which voxels
            to fill

        x, y, z : 3D np.array, optional
            The coordinates of the corners of the voxels. This should broadcast
            to a shape one larger in every dimension than the shape of
            *filled*.  These can be used to plot non-cubic voxels.

            If not specified, defaults to increasing integers along each axis,
            like those returned by :func:`~numpy.indices`.
            As indicated by the ``/`` in the function signature, these
            arguments can only be passed positionally.

        facecolors, edgecolors : array-like, optional
            The color to draw the faces and edges of the voxels. Can only be
            passed as keyword arguments.
            These parameters can be:

            - A single color value, to color all voxels the same color. This
              can be either a string, or a 1D rgb/rgba array
            - ``None``, the default, to use a single color for the faces, and
              the style default for the edges.
            - A 3D ndarray of color names, with each item the color for the
              corresponding voxel. The size must match the voxels.
            - A 4D ndarray of rgb/rgba data, with the components along the
              last axis.

        shade : bool, default: True
            Whether to shade the facecolors.  Shading is always disabled when
            *cmap* is specified.

        lightsource : `~matplotlib.colors.LightSource`
            The lightsource to use when *shade* is True.

        **kwargs
            Additional keyword arguments to pass onto
            `~mpl_toolkits.mplot3d.art3d.Poly3DCollection`.

        Returns
        -------
        faces : dict
            A dictionary indexed by coordinate, where ``faces[i, j, k]`` is a
            `.Poly3DCollection` of the faces drawn for the voxel
            ``filled[i, j, k]``. If no faces were drawn for a given voxel,
            either because it was not asked to be drawn, or it is fully
            occluded, then ``(i, j, k) not in faces``.

        Examples
        --------
        .. plot:: gallery/mplot3d/voxels.py
        .. plot:: gallery/mplot3d/voxels_rgb.py
        .. plot:: gallery/mplot3d/voxels_torus.py
        .. plot:: gallery/mplot3d/voxels_numpy_logo.py
        r   c                 [   s   | ||f||fS rv   r_   )Z
_Axes3D__xZ
_Axes3D__yZ
_Axes3D__zrz  r\   r_   r_   r`   voxelsV
  s    zAxes3D.voxels.<locals>.voxelsc                 [   s
   d | |fS rv   r_   )rz  r\   r_   r_   r`   r  Y
  s    z%Argument filled must be 3-dimensionalr   r   Nc                 3   s   | ]}t | V  qd S rv   )r   r  )r   ru  )coord_shaper_   r`   r   h
  rx   z Axes3D.voxels.<locals>.<genexpr>c                    sp   t | dv r&t |  jt |  S t | dv r^t | d d  jkrZtd|| S td|d S )N)r   r   )r   r   r   z8When multidimensional, {} must match the shape of filledzInvalid {} argument)r   r  r  r  r   format)r  name)rz  r_   r`   _broadcast_color_argj
  s    z+Axes3D.voxels.<locals>._broadcast_color_argr  rD  r  r  r  r  c                 s   s8   t j| t jd}t| D ]}|V  t j|ddd}qdS )z%Generate cyclic permutation matrices.r   r   r   r   N)r   rN  intpr  r   )r  matr   r_   r_   r`   permutation_matrices
  s    z+Axes3D.voxels.<locals>.permutation_matricesrI  r   r   rC  )r   r  r   r   r   r  r  r/  indicesr  r  r  r   r  r  rR  aranger  r  itemsr  r  r  r   r  rK  )2rX   r  rD  r  r  r[   r\   r  Zxyzr5  r   r   r   r  squareZvoxel_facesr  permutepcZqcrcZpindsZqindsZrindsZsquare_rot_posZsquare_rot_negr  qrT  i0r1r2rU  rV  r  r  pkZpk2ikr  coordZ
faces_indsZfacesZ	face_indsindfacerv  	edgecolorr'  polyr_   )r  rz  r`   r  
  s    H




	





"

.


zAxes3D.voxels)r   r   r   xerryerrzerrr  c           C   	      sX  |   }t|tj}dd | D }|dd | jd|fd|fd|fg|dd	 t	|rd|n|g}t	|rx|n|g}t	|r|n|g}t
|t
|  krt
|ksn td
| ||	|dd}d|d< | jj|dkr||fn|||f|dd\\}}tj||d |r2||d d  n||d d  | dkr^| | nd}|d d|vr~d|d< |
du r|d }
dD ]}||d qi |d|
i}|r||d< nd|v r|d |d< dD ]}||v r|| ||< qi |ddi}|du r$tjd }|dkr:d| |d< |durL||d< |
|d< d d! }fd"d# g g g   }}}g } d$d$d%d&}!dd'dd(|dtjd) d }"|"| jjd* 9 }"| j d+|"|"fg}"ttj|"dd,}"tj| dddd-  tj !| " }#W d   n1 s 0    Y  t#|#t$|"dddgd' }"|"d.9 }"i ||"d'd/}$|$dd t%g d(|||g|||g|||g|||gD ]\}%}&t&|%|% }'du rʐqt	sgt
|& t't(t
|&)t*t(t
|&)t* fd0d1t+|||gD }(|(\\})}*\}+},\}-}.B  }/|/, r|dkr||)|+|-g|/@ }0||*|,|.g|/@ }1tj-|0d|!|' d2|}2tj-|1d|!|' d2|}3| |2 | |3 |.|2 |.|3 , r6||*|,|.g@ \}4}5}6| j/|4|5|6gR i |$ , rx||)|+|-g@ \}7}8}9| j/|7|8|9g R i |$ tj0t$|(j1fi |}:| 2|: |.|: | .|( qt$| } fd3d4};|;| d\}<}=|;| d\}>}?|;| d\}@}A| 3|<|=f|>|?f|@|Af| t4j5|t6|t6|f|dup4|du|du|d5}B| j7.|B |||fS )6a  
        Plot lines and/or markers with errorbars around them.

        *x*/*y*/*z* define the data locations, and *xerr*/*yerr*/*zerr* define
        the errorbar sizes. By default, this draws the data markers/lines as
        well the errorbars. Use fmt='none' to draw errorbars only.

        Parameters
        ----------
        x, y, z : float or array-like
            The data positions.

        xerr, yerr, zerr : float or array-like, shape (N,) or (2, N), optional
            The errorbar sizes:

            - scalar: Symmetric +/- values for all data points.
            - shape(N,): Symmetric +/-values for each data point.
            - shape(2, N): Separate - and + values for each bar. First row
              contains the lower errors, the second row contains the upper
              errors.
            - *None*: No errorbar.

            Note that all error arrays should have *positive* values.

        fmt : str, default: ''
            The format for the data points / data lines. See `.plot` for
            details.

            Use 'none' (case insensitive) to plot errorbars without any data
            markers.

        ecolor : color, default: None
            The color of the errorbar lines.  If None, use the color of the
            line connecting the markers.

        elinewidth : float, default: None
            The linewidth of the errorbar lines. If None, the linewidth of
            the current style is used.

        capsize : float, default: :rc:`errorbar.capsize`
            The length of the error bar caps in points.

        capthick : float, default: None
            An alias to the keyword argument *markeredgewidth* (a.k.a. *mew*).
            This setting is a more sensible name for the property that
            controls the thickness of the error bar cap in points. For
            backwards compatibility, if *mew* or *markeredgewidth* are given,
            then they will over-ride *capthick*. This may change in future
            releases.

        barsabove : bool, default: False
            If True, will plot the errorbars above the plot
            symbols. Default is below.

        xlolims, ylolims, zlolims : bool, default: False
            These arguments can be used to indicate that a value gives only
            lower limits. In that case a caret symbol is used to indicate
            this. *lims*-arguments may be scalars, or array-likes of the same
            length as the errors. To use limits with inverted axes,
            `~.Axes.set_xlim` or `~.Axes.set_ylim` must be called before
            `errorbar`. Note the tricky parameter names: setting e.g.
            *ylolims* to True means that the y-value is a *lower* limit of the
            True value, so, only an *upward*-pointing arrow will be drawn!

        xuplims, yuplims, zuplims : bool, default: False
            Same as above, but for controlling the upper limits.

        errorevery : int or (int, int), default: 1
            draws error bars on a subset of the data. *errorevery* =N draws
            error bars on the points (x[::N], y[::N], z[::N]).
            *errorevery* =(start, N) draws error bars on the points
            (x[start::N], y[start::N], z[start::N]). e.g. errorevery=(6, 3)
            adds error bars to the data at (x[6], x[9], x[12], x[15], ...).
            Used to avoid overlapping error bars when two series share x-axis
            values.

        Returns
        -------
        errlines : list
            List of `~mpl_toolkits.mplot3d.art3d.Line3DCollection` instances
            each containing an errorbar line.
        caplines : list
            List of `~mpl_toolkits.mplot3d.art3d.Line3D` instances each
            containing a capline object.
        limmarks : list
            List of `~mpl_toolkits.mplot3d.art3d.Line3D` instances each
            containing a marker with an upper or lower limit.

        Other Parameters
        ----------------
        data : indexable object, optional
            DATA_PARAMETER_PLACEHOLDER

        **kwargs
            All other keyword arguments for styling errorbar lines are passed
            `~mpl_toolkits.mplot3d.art3d.Line3DCollection`.

        Examples
        --------
        .. plot:: gallery/mplot3d/errorbar3d.py
        c                 S   s   i | ]\}}|d ur||qS rv   r_   )r   r  r  r_   r_   r`   
<dictcomp>S  rx   z#Axes3D.errorbar.<locals>.<dictcomp>r   r   r   r   r   F)convertz)'x', 'y', and 'z' must have the same sizer  N
_nolegend_r  T)return_kwargs)r  g?noner  C0)marker
markersizemarkerfacecolormarkeredgewidthmarkeredgecolor	markevery	linestyle	fillstyle	drawstyledash_capstyledash_joinstylesolid_capstylesolid_joinstyle	linewidth)rQ   r)  r   
rasterizedr  Nonezerrorbar.capsizer   r   r  r  c                    s    fdd| D S )Nc                    s   g | ]}g t | qS r_   )r  compress)r   r   r  r_   r`   r    rx   z8Axes3D.errorbar.<locals>._apply_mask.<locals>.<listcomp>r_   )arraysr(  r_   r  r`   _apply_mask  s    z$Axes3D.errorbar.<locals>._apply_maskc                    sZ   t | jdkr| \}}n
| |  }}t|  B ||| }t|  B ||| }||fS r  )r   r  r   r  )errdataZlomaskZhimaskZlow_errZhigh_errZlowsZhighs)	everymaskr_   r`   _extract_errs  s    

z&Axes3D.errorbar.<locals>._extract_errs|_r   r   r   zlines.markersizeH   r,   r   )r   r   r   gV&,t=?)r  r  c                    s&   g | ]\}} |  |qS r_   r_   )r   r   r  )r  
dir_vectorr  lolimsuplimsr_   r`   r    s   z#Axes3D.errorbar.<locals>.<listcomp>)lsr  c              	      sL   t | d d  | d d d d f t | d d  | d d d d f fS rv   rf  )Zerr_arrZcoord_label)i_xyzr_   r`   _digout_minmax  s    $$z'Axes3D.errorbar.<locals>._digout_minmax)has_xerrhas_yerrr  )8r  r   normalize_kwargsr  r  r  
setdefault_process_unit_infor   r*  r   r   _errorevery_to_maskr=   r  
_plot_argsr   r  
set_zorderr  add_linerm  rn  r  rE   dpi	transAxesrP   rQ   r   rZ  _setattr_cmr   invr   rR  r   r  Zget_dir_vectorr[  r  r  r   r   r  ZLine3Dr  r  r6  r  r   r  
mcontainerErrorbarContainerr/  
containers)CrX   r   r   r   r  r  r  fmt	barsabove
erroreveryecolor
elinewidthcapsizecapthickxlolimsxuplimsZylolimsZyuplimsZzlolimsZzuplimsr\   r  r  	data_line
base_styler   eb_lines_styleeb_cap_styler  ZerrlinescaplinesZlimmarksZ	coorderrsZ	capmarkerZ
quiversizeZinvMZeb_quiver_styler  r  Zi_zdirZcoorderrr1  xhr2  Zyhr3  zhnolimsZlo_caps_xyzZhi_caps_xyzcap_locap_hiZxh0Zyh0Zzh0Zxl0Zyl0Zzl0Zerrliner  r{   r|   r}   r~   r   r   errorbar_containerr_   )r  r  r  r  r  r  r  r`   errorbar
  s
   k"










0












zAxes3D.errorbar)for_layout_onlyc          	         s^   t  j||||d}|g}| jrR| j D ]&}| r*t||}|r*|| q*t	j
|S )N)call_axes_locatorbbox_extra_artistsr-  )r>   get_tightbboxrb   r   r   r   martist_get_tightbbox_for_layout_onlyr  r   r
   union)	rX   r   r.  r/  r-  r  batchr   Zaxis_bbr]   r_   r`   r0  (  s    zAxes3D.get_tightbboxzC0-ZC0ozC3-)linefmt	markerfmtbasefmtr,  r  orientationc                   s  ddl m}
 |  }tjg d|	d t|t|f}t|t|f}t|t|f}|	dkr|| }}|| }} fddt|||D }nf|	dkr|| }}|| }} fd	dt|||D }n.|| }}|| }} fd
dt|||D }t	|\}}}|du r"t
jd }| j||| |	dd\}tj|||dd}| | | j||||dd\}|
|||f|d}| | t||  g|	\}}}| g ||g ||g ||| |S )a  
        Create a 3D stem plot.

        A stem plot draws lines perpendicular to a baseline, and places markers
        at the heads. By default, the baseline is defined by *x* and *y*, and
        stems are drawn vertically from *bottom* to *z*.

        Parameters
        ----------
        x, y, z : array-like
            The positions of the heads of the stems. The stems are drawn along
            the *orientation*-direction from the baseline at *bottom* (in the
            *orientation*-coordinate) to the heads. By default, the *x* and *y*
            positions are used for the baseline and *z* for the head position,
            but this can be changed by *orientation*.

        linefmt : str, default: 'C0-'
            A string defining the properties of the vertical lines. Usually,
            this will be a color or a color and a linestyle:

            =========  =============
            Character  Line Style
            =========  =============
            ``'-'``    solid line
            ``'--'``   dashed line
            ``'-.'``   dash-dot line
            ``':'``    dotted line
            =========  =============

            Note: While it is technically possible to specify valid formats
            other than color or color and linestyle (e.g. 'rx' or '-.'), this
            is beyond the intention of the method and will most likely not
            result in a reasonable plot.

        markerfmt : str, default: 'C0o'
            A string defining the properties of the markers at the stem heads.

        basefmt : str, default: 'C3-'
            A format string defining the properties of the baseline.

        bottom : float, default: 0
            The position of the baseline, in *orientation*-coordinates.

        label : str, default: None
            The label to use for the stems in legends.

        orientation : {'x', 'y', 'z'}, default: 'z'
            The direction along which stems are drawn.

        data : indexable object, optional
            DATA_PARAMETER_PLACEHOLDER

        Returns
        -------
        `.StemContainer`
            The container may be treated like a tuple
            (*markerline*, *stemlines*, *baseline*)

        Examples
        --------
        .. plot:: gallery/mplot3d/stem3d_demo.py
        r   )StemContainerr   )r8  r   c                    s&   g | ]\}}} ||f|||fgqS r_   r_   r   thisxthisyZthiszr,  r_   r`   r    s   zAxes3D.stem.<locals>.<listcomp>r   c                    s&   g | ]\}}}| |f|||fgqS r_   r_   r:  r=  r_   r`   r    s   c                    s&   g | ]\}}}|| f|||fgqS r_   r_   r:  r=  r_   r`   r    s   Nzlines.linestyler  )r  r  r  )
linestylesr*  r  )r  )matplotlib.containerr9  r  r   r   r   r  r   r  r	   rm  rn  r  r   r6  r   add_containerr  r  )rX   r   r   r   r5  r6  r7  r,  r  r8  r9  r  r   r   r   basexZbasexlimbaseyZbaseylimr  r  
linemarker	linecolorbaseline	stemlines
markerlinestem_containerZjxjyZjzr_   r=  r`   stem8  sV    B

















(zAxes3D.stem)N)N)NN)NN)NNF)N)Tr   N)NN)NTTT)NNTF)NNNr   )N)r   r   )NN)T)r   )NN)N)N)r   )Fr   r   N)r   N)r   N)r   r   )r   r   rx  NT)r   r   )Nr  TN)Nr  )NNNr  Fr   NNNNFFFFFF)NTN)__name__
__module____qualname____doc__r  _axis_namesr   Grouperr   r:   r   deprecate_privatize_attributedistr?   r@   rA   rg   rL   rp   rr   r   Zget_zgridlinesZget_zticklines
deprecatedpropertyZw_xaxisZw_yaxisZw_zaxisr   r   r   r   r   r   r1  allow_rasterizationr   r   r   r  r  r   r   r  r  r   ry   make_keyword_onlyr.  rf  set_xlimr   set_ylimr   r   r0  r1  r2  Z
get_zscale
set_xscale
set_yscaleZ
set_zscalemapr  Z
get_zticksZ
set_zticksZget_zmajorticklabelsZget_zminorticklabelsZget_zticklabelsZset_zticklabelsZ
zaxis_datetextwrapdedentr=  r8   r2   rG  r   rD   ra  rb  rc  r   rl  rJ   rK   r}  r  r  r  rI   r  r  r  r  rename_parameterro  r  r  r  r  r  r  Ztext3DZtext2Dr  Zplot3Dr  r  r  r9  rB  rR  rV  rY  rX  r   ra  Z	contour3Dre  rl  rm  Z
contourf3Drn  rK  r  Z	scatter3Dr  r  r  r  Zquiver3Dr  r,  r0  rJ  Zstem3D__classcell__r_   r_   r]   r`   r   *   sf  
 
 







Q'
7

$
#
  
>











F
E
	(L
	


) J+
$ve
4 

%4
0!G5  &  Y     E tr   r~  c                 C   s   t dd|  }}t ||\}}t |d |d   d dt j  }t |d d d |d d d   d dt j d d  }|| }|d }|d }|d }|||fS )	z,Return a tuple X, Y, Z with a test data set.g      g      @r   r   g      ?rH  r>  i  )r   r  meshgridexprQ  )r   r   r   r  r  ZZ1ZZ2r  r_   r_   r`   get_test_data  s    &*rb  )r~  )8rN  rF  r   r  r  r  r\  numpyr   
matplotlibrm  r   r   r   r   matplotlib.artistr   r1  matplotlib.axesaxesrf  matplotlib.collectionsr   matplotlib.colorsr*  r  matplotlib.imageimager  matplotlib.linesr  r  matplotlib.patchesr  r   r?  	containerr  matplotlib.transforms
transformsr   r   matplotlib.axes._baser   r	   r
   Zmatplotlib.tri.triangulationr   r  r   r   r   interpddefine_aliasesr   rb  r_   r_   r_   r`   <module>   sn                            