U
    SZf                     @   s   d dl mZmZ d dlmZ d dlmZ d dlm	Z	 d dl
Z
d dlmZ edZdZdZd	Zd
ZdZdZdZdZdZdZdZdZdZdddddgZdZdd Zdd Zdd Z d3d!d"Z!d#d$ Z"d4d&d'Z#d(d) Z$d*d+ Z%d,d- Z&d.d/ Z'd5d1d2Z(dS )6    )
exceptionsoptional_importsN)utils)make_subplots)NumberZpandasz#969696z#0f0f0f   z#ffffffz#efefefz#edededz#d0d0d0   ?      ?   
   scatter	scattergl	histogrambarZboxzIf you are using a dictionary for custom labels for the facet row/col, make sure each key in that column of the dataframe is in your facet labels. The keys you need are {}c                 C   s   | t krd}nd}|S )NTF)THRES_FOR_FLIPPED_FACET_TITLES)numflipped r   E/tmp/pip-unpacked-wheel-5ksk5baj/plotly/figure_factory/_facet_grid.py_is_flipped"   s    r   c                 C   s4   t |tr||  }nt |tr,d|| }n| }|S )Nz{}: {})
isinstancedictstrformat)Zoriginal_labelZfacet_labelsZ	facet_varlabelr   r   r   _return_label*   s    


r   c                 C   s.   t dddtddddd| t dd	d
d
}|S )Nr   leftmiddle{Gz?Fpaperz
factor({})   #000000sizecolor
	textanglexanchoryanchorxy	showarrowxrefyreftextfont)r   LEGEND_ANNOT_Xr   )
color_nameZlegend_titler   r   r   _legend_annotation4   s    
r3   colTc                 C   s  d|d |  | }|std}d}|dkrJ|d ||  d|  }	d}
d}q|dkr|d ||  d|  }
d}	d	}nb|dkrd}d
}|d ||  d|  }	d}
d}n0|dkrd}d}|d ||  d|  }
d}	d}t ||||	|
dddt| t dtdd
}|S )Nr   centerr   r4   r
   r   r   rowZ   Zbottom      ?  r   Fr    r!   r#   r&   )r   r   AXIS_TITLE_COLOR)r/   ZlaneZnum_of_lanesSUBPLOT_SPACINGrow_colr   lr(   r)   r*   r+   r'   Zannotation_dictr   r   r   _annotation_dictD   sJ    
r>   c                 C   sV   |dkrd}d}d}n|dkr*d}d}d}| s2d} dt d	d
| ||dd|ddd
}|S )Nr*   r
   gr   r+   r9    r"   r%   r$   Fr5   r    r   )
r0   r,   r/   r'   r*   r(   r-   r+   r)   r.   )AXIS_TITLE_SIZE)r/   Zx_or_y_axisZx_posZy_posr'   Zannotr   r   r   _axis_title_annotationp   s,    rB   Fc                 C   s4  g }| d    D ]}d|kr| d | d ddgkr|d|ddd	d
d
d}d|kr| d | d d |d< | d | d d |d< d|d< d|d< |r|d  d7  < || qd|krd|d< d|d< | d | d d |d< | d | d d |d< |r|d  d7  < || q|| d d< d S )NlayoutZaxisdomaing        r8   Zbelowr   r%   widthZrectr    )Z	fillcolorZlayerlinetyper-   r.   xaxisr   Zx0x1gGz?Zy0r	   y1r
   yaxisZshapes)Zto_plotly_jsonkeysappend)figZannot_rect_colorflipped_rowsflipped_colsZshapes_listkeyshaper   r   r   _add_shapes_to_fig   s6     	rT   c                 K   s*   |dkr&d| d< t f d|i|| d< | S )Nr   r   markersmoder%   marker)r   )trace
trace_typer%   kwargs_markerr   r   r   _make_trace_for_scatter   s    r\   c           )      C   s  t ||dd||dd}g }|s|st| |}|D ]z}tf ||d t||d  dd|}|rt|d | |d< |r|d | |d	< t||||d  f|}||dd q4nT|r|r|s|rt| |r|n|}t|D ]\}}| |  D ]}|d |d | |k }tf ||t|| dd|}|rJ|| |d< |r\|| |d	< t|||| f|}|||r|d nd|rdn|d  qt|d |r|	n|
|r|n|}|	t
||r|| n|d |r|n|||rd
nd| qn|r|rt| ||g}dd |D }| |  }| |  } | |  }!t|D ]\}"}#t| D ]d\}$}%z||#|%f }W n2 tk
r   tjd d d gg|||gd}Y nX |!D ]}|j d d d ggkr||| |k }&tf ||t|| dd|}|&| }'|&| }(n2tf ||t|| ddd|}|| }'|| }(|r^|'|d< |rl|(|d	< t|||| f|}|||"d |$d  q|"dkrnt| |$ |
|}|	t
||$d ||d|d qnt||" |	|}|	t
|||" ||d
|d q\||fS )NTFZrowscolsZshared_xaxesZshared_yaxesZhorizontal_spacingZvertical_spacingZ
print_gridr   )r%   )rH   namerX   r   r*   r+   r6   r4   c                 S   s   i | ]}|d  |d qS r   r   r   .0itemr   r   r   
<dictcomp>  s      z1_facet_grid_color_categorical.<locals>.<dictcomp>columns)rH   r_   rX   
showlegendr<   r   )r   listgroupbyr   r\   append_trace	enumerateuniquer   rN   r>   KeyErrorpd	DataFramevaluestolist))dfr*   r+   	facet_row	facet_colr2   colormapnum_of_rowsnum_of_colsfacet_row_labelsfacet_col_labelsrZ   rP   rQ   
show_boxesr;   marker_colorkwargs_tracer[   rO   annotationsZcolor_groupsgrouprY   groups_by_facetjZ	color_valZdata_by_colorr   groups_by_facetstuple_to_facet_group
row_values
col_valuesZ
color_vals	row_countx_val	col_county_valZgroup_filteredZnew_xZnew_yr   r   r   _facet_grid_color_categorical   s0   
  
    

 
  
  
r   c           #      C   s  t ||dd||dd}g }|s|stf |t| | |ddd|}|rT| | |d< |rd| | |d< t||| | f|}||dd |r|r|s|rt| |r|n|}t|D ]\}}tf |t| | |dtd	d
dd|}|r|d | |d< |r|d | |d< t||| | f|}|||r@|d nd|rLdn|d  |r`|	n|
}t|d ||rx|n|}|t	||r|| n|d |r|n|||rdnd|d qn|r|rt| ||g}dd |D }| | 
 }| | 
 }t|D ]x\}} t|D ]0\}!}"z|| |"f }W n2 tk
rn   tjd d d gg|||gd}Y nX |j d d d ggkrtf |t| | ||dktd	d
dd|}ntf |dd|}|r|| |d< |r|| |d< t||| | f|}|||d |!d  |dkr"t||! |
|}|t	||!d ||d|d q"t|| |	|}|t	|| || ||d|d q||fS )NTFr]   )r%   
colorscale	showscalerH   rX   r*   r+   r   gffffff?)r*   )r%   r   r   Zcolorbarr   r6   r4   )r   c                 S   s   i | ]}|d  |d qS r`   r   ra   r   r   r   rd     s      z/_facet_grid_color_numerical.<locals>.<dictcomp>re   )rH   rg   rh   )r   r   r\   rk   ri   rj   rl   r   rN   r>   rm   rn   ro   rp   rq   rr   )#rs   r*   r+   rt   ru   r2   rv   rw   rx   ry   rz   rZ   rP   rQ   r{   r;   r|   r}   r[   rO   r~   rY   r   r   r   labelsr   r   r   r   r   r   r   r   r   r   r   r   _facet_grid_color_numerical`  s   
  
      

   
  
r   c                  C   s0  t ||dd||dd}g }|s|stf |	t||d dd|}|rR| | |d< |rb| | |d< t||	|f|}||d	d	 n|r|r|s|rt| |r|n|}t|D ]\}}tf |	t||d dd|}|r|d	 | |d< |r|d	 | |d< t||	|f|}|||r,|d	 nd	|r8d	n|d	  t|d
 |rT|n||r`|n|}|t	||r||| n|d	 |r|n|||rdnd|
 qn~|r(|r(t| ||g}dd |D }| | 
 }| | 
 }t|D ].\}}t|D ]\}}z|||f }W n. tk
rN   tjd d gg||gd}Y nX tf |	t||d dd|}|r|| |d< |r|| |d< t||	|f|}|||d	 |d	  |d
krt|| ||}|t	||d	 ||d|d qt|| ||}|t	||| ||d|
d q||fS )NTFr]   rG   )r%   rG   r   r*   r+   r   r   r6   r4   c                 S   s   i | ]}|d  |d qS r`   r   ra   r   r   r   rd   U  s      z_facet_grid.<locals>.<dictcomp>re   rh   )r   r   r\   rk   ri   rj   rl   r   rN   r>   rm   rn   ro   rp   ) rs   r*   r+   rt   ru   rw   rx   ry   rz   rZ   rP   rQ   r{   r;   r|   r}   r[   rO   r~   rY   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   _facet_grid  s    	      
  
  r   fixedc           7      K   s	  t stdt| t js"tdt|  |dkrF|r<|sFtd|||||fD ]8}|dk	rTz| |  W qT tk
r   tdY qTX qT|dkrd}|dkrtd	|t	krtd

t	|dkrd}nd}d|kr|d }ni }|dd}|dd |}d|kr*|r"d|d< nd|d< d|krB|sBd|d< d|krj|sbddd|d< ni |d< |s||sd}nd}d}d}d}d}|rt| |  }t|}t|tr| |  D ]4}|| kr| |   }tt
|q|rht| |  }t|}t|	trh| |  D ]4}||	 kr2| |   }tt
|q2d}|rt| | jd ts|rTd}t|trt|d | |  D ]}|| krtdqnHtj} i }d}!| |  D ],}|!t| krd}!| |! ||< |!d7 }!qt| ||||||||||	||||||||\}"}#qt| | jd trt|trd}t|d | |  D ]}|| krtdqt| ||||||||||	||||||||\}"}#nt|tr0|}$t|$ t| ||||||$||||	||||||||\}"}#nt|tr|tj krXtj| }$ntd 
tj t| ||||||$||||	||||||||\}"}#n:tjd! }$t| ||||||$||||	||||||||\}"}#n,t| ||||||||	||||||||\}"}#|
std"d#| }
|s0td"d#| }|"d$ j |
|d%d&d' |r`|"d$ j t!d(d)d* t"|d+}%t"|d,}&|##|% |##|& ||"d$ d-< t$|"d$ d. d/< t%|"d$ d. d0< d1|"d$ d. d+< d|"d$ d. d,< d2|"d$ d. d3< |r$||"d$ d-< |r$|rt&|}'|##|' d4|"d$ d5 d6< |#|"d$ d7< |rJ|rJt'|"t(|| g g d8}(|"d$ D ]8}d9|krz|(d+ #| nd:|kr\|(d, #| q\d})d;d< ||fD D ]V}*t| |*  d tr| |* D ].}+zt)|+ d})W n t*k
r   Y nX qАq|)r:|( D ]&},|(|, D ]}-d=|"d$ |- d>< qq|d?krNd+d,g}.n2|d@kr`d,g}.n |dAkrrd+g}.n|dkrg }.|.D ]:},g }/g }0|"dB D ]J}1|1|, dk	rt|1|, dkr|/#t+|1|,  |0#t|1|,  qd|/kr|/,d qd|0kr|0,d qt+|/}2t|0}3t|2to:t|3t}4|4rt-.|2}2t-/|3}3|2dC|3|2  8 }2|3dC|3|2  7 }3|,d+kr|r|}5nt-.|3|2 t0 }5n(|,d,kr|r|}5nt-.|3|2 t0 }5nd}5|(|, D ]}6|5|"d$ |6 dD< d|"d$ |6 dE< d|"d$ |6 dF< |rd|"d$ |6 dG< dH|"d$ |6 dE< t1|"d$ |6 dI< t2|"d$ |6 dJ< dK|"d$ |6 dI< t3dLdM|"d$ |6 dN< q|,|.kr|"d$ D ]0}dO
|,|k	r|4	r|2|3g|"d$ | dP< 	qq|"S )Qai  
    Returns figure for facet grid; **this function is deprecated**, since
    plotly.express functions should be used instead, for example

    >>> import plotly.express as px
    >>> tips = px.data.tips()
    >>> fig = px.scatter(tips,
    ...     x='total_bill',
    ...     y='tip',
    ...     facet_row='sex',
    ...     facet_col='smoker',
    ...     color='size')


    :param (pd.DataFrame) df: the dataframe of columns for the facet grid.
    :param (str) x: the name of the dataframe column for the x axis data.
    :param (str) y: the name of the dataframe column for the y axis data.
    :param (str) facet_row: the name of the dataframe column that is used to
        facet the grid into row panels.
    :param (str) facet_col: the name of the dataframe column that is used to
        facet the grid into column panels.
    :param (str) color_name: the name of your dataframe column that will
        function as the colormap variable.
    :param (str|list|dict) colormap: the param that determines how the
        color_name column colors the data. If the dataframe contains numeric
        data, then a dictionary of colors will group the data categorically
        while a Plotly Colorscale name or a custom colorscale will treat it
        numerically. To learn more about colors and types of colormap, run
        `help(plotly.colors)`.
    :param (bool) color_is_cat: determines whether a numerical column for the
        colormap will be treated as categorical (True) or sequential (False).
            Default = False.
    :param (str|dict) facet_row_labels: set to either 'name' or a dictionary
        of all the unique values in the faceting row mapped to some text to
        show up in the label annotations. If None, labeling works like usual.
    :param (str|dict) facet_col_labels: set to either 'name' or a dictionary
        of all the values in the faceting row mapped to some text to show up
        in the label annotations. If None, labeling works like usual.
    :param (int) height: the height of the facet grid figure.
    :param (int) width: the width of the facet grid figure.
    :param (str) trace_type: decides the type of plot to appear in the
        facet grid. The options are 'scatter', 'scattergl', 'histogram',
        'bar', and 'box'.
        Default = 'scatter'.
    :param (str) scales: determines if axes have fixed ranges or not. Valid
        settings are 'fixed' (all axes fixed), 'free_x' (x axis free only),
        'free_y' (y axis free only) or 'free' (both axes free).
    :param (float) dtick_x: determines the distance between each tick on the
        x-axis. Default is None which means dtick_x is set automatically.
    :param (float) dtick_y: determines the distance between each tick on the
        y-axis. Default is None which means dtick_y is set automatically.
    :param (bool) show_boxes: draws grey boxes behind the facet titles.
    :param (bool) ggplot2: draws the facet grid in the style of `ggplot2`. See
        http://ggplot2.tidyverse.org/reference/facet_grid.html for reference.
        Default = False
    :param (int) binsize: groups all data into bins of a given length.
    :param (dict) kwargs: a dictionary of scatterplot arguments.

    Examples 1: One Way Faceting

    >>> import plotly.figure_factory as ff
    >>> import pandas as pd
    >>> mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt')

    >>> fig = ff.create_facet_grid(
    ...     mpg,
    ...     x='displ',
    ...     y='cty',
    ...     facet_col='cyl',
    ... )
    >>> fig.show()

    Example 2: Two Way Faceting

    >>> import plotly.figure_factory as ff

    >>> import pandas as pd

    >>> mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt')

    >>> fig = ff.create_facet_grid(
    ...     mpg,
    ...     x='displ',
    ...     y='cty',
    ...     facet_row='drv',
    ...     facet_col='cyl',
    ... )
    >>> fig.show()

    Example 3: Categorical Coloring

    >>> import plotly.figure_factory as ff
    >>> import pandas as pd
    >>> mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv')
    >>> mtcars.cyl = mtcars.cyl.astype(str)
    >>> fig = ff.create_facet_grid(
    ...     mtcars,
    ...     x='mpg',
    ...     y='wt',
    ...     facet_col='cyl',
    ...     color_name='cyl',
    ...     color_is_cat=True,
    ... )
    >>> fig.show()


    z3'pandas' must be installed for this figure_factory.z"You must input a pandas DataFrame.rU   z`You need to input 'x' and 'y' if you are you are using a trace_type of 'scatter' or 'scattergl'.NzIx, y, facet_row, facet_col and color_name must be keys in your dataframe.free)r   free_xfree_yr   z?'scales' must be set to 'fixed', 'free_x', 'free_y' and 'free'.z'trace_type' must be in {}r   gQ?gQ?rX   r%   r$   r      Zopacityg333333?rG   Zdarkgreyr   rE   zrgb(31, 119, 180)zrgb(0, 0, 0)Fr   TZrgbzxIf using 'colormap' as a dictionary, make sure all the values of the colormap column are in the keys of your dictionary.zlIf 'colormap' is a string, it must be the name of a Plotly Colorscale. The available colorscale names are {}ZRedsiX  d   rC   r?   zrgb(251, 251, 251))heightrF   titlepaper_bgcolorzrgb(255, 255, 255)Zclosest)Zplot_bgcolorr   Z	hovermoder*   r+   rg   ZlegendZbgcolorZborderwidthr	   topr)      marginrr~   )r*   r+   rI   rL   c                 S   s   g | ]}|r|qS r   r   )rb   vr   r   r   
<listcomp>X  s      z%create_facet_grid.<locals>.<listcomp>categoryrH   r   r   r   datag?dtickZticklenZzerolineZ	tickwidth   Z	gridwidthZ	gridcolor   r   r@   Ztickfontz{}axisrange)4ro   ImportErrorr   rp   r   ZPlotlyErrorr   Zvalidate_dataframern   VALID_TRACE_TYPESr   poplenrm   r   r   rM   rr   CUSTOM_LABEL_ERRORZilocr   clrsZvalidate_colors_dictZDEFAULT_PLOTLY_COLORSr   r   ri   Zvalidate_colorscaler   ZPLOTLY_SCALESr   maxupdatePLOT_BGCOLORrB   rN   LEGEND_COLORLEGEND_BORDER_WIDTHr3   rT   ANNOT_RECT_COLORint
ValueErrorminremovemathfloorceilMAX_TICKS_PER_AXIS
GRID_WIDTH
GRID_COLOR
TICK_COLOR)7rs   r*   r+   rt   ru   r2   rv   Zcolor_is_catry   rz   r   rF   rZ   ZscalesZdtick_xZdtick_yr{   Zggplot2ZbinsizekwargsrR   r;   r[   r|   r}   rw   rx   rP   rQ   Zunique_keysZshow_legendvalZdefault_colorsr   rO   r~   Zcolorscale_listZx_title_annotZy_title_annotZlegend_annotZaxis_labelsZstring_number_in_datavarrc   Zx_yZ	axis_nameZ
fixed_axesZ
min_rangesZ
max_rangesrY   Z	min_rangeZ	max_rangeZrange_are_numbersr   Z
axis_titler   r   r   create_facet_grid  s    













   













 

 




r   )r4   T)FF)NNNNNNFNNNNr   r   NNTFr   ))Zplotlyr   r   Zplotly.colorscolorsr   Zplotly.figure_factoryr   Zplotly.subplotsr   r   Znumbersr   Z
get_modulero   r   r:   rA   r   r   r   r   r   r1   ZLEGEND_ANNOT_Yr   r   r   r   r   r   r   r3   r>   rB   rT   r\   r   r   r   r   r   r   r   r   <module>   sp   

   
,
$ *                    