B
    &[_                 @   s  d dl mZ 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"d4d"d#Z#d$d% Z$d5d'd(Z%d)d* Z&d+d, Z'd-d. Z(d/d0 Z)d6d2d3Z*dS )7    )absolute_import)
exceptionsoptional_importsN)utils)make_subplots)NumberZpandasz#969696z#0f0f0f   z#ffffffz#efefefz#edededz#d0d0d0   g?g      ?   
   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-install-l29rncou/plotly/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middleg{Gz?Fpaperz
factor({})   z#000000)sizecolor)
	textanglexanchoryanchorxy	showarrowxrefyreftextfont)r   LEGEND_ANNOT_Xr   )
color_nameZlegend_titler   r   r   _legend_annotation6   s    r.   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   r/   g      ?g{Gz?r   rowZ   Zbottomg      ?i  r   Fr   r   )r    r!   )
r"   r#   r$   r%   r&   r'   r(   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_dictF   sH    r7   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%   g      ?gr   r&   i   z#000000)r!   r    Fr0   r   r   )
r+   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_annotationr   s*    r:   Fc             C   s:  g }x"| 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W || d d< d S )NlayoutZaxisdomaing        g      ?Zbelowr	   )r!   widthZrectr   )Z	fillcolorZlayerlinetyper(   r)   xaxisr   Zx0x1gGz?Zy0g?y1g      ?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   s4     rK   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    rR   c       )      C   s0  t ||dd||dd}g }|s|st| |}x|D ]z}tf ||d t||d  dd|}|rv|d | |d< |r|d | |d	< t||||d  f|}||dd q6W np|r|r|s|rt| |r|n|}xBt|D ]\}}x| |  D ]}|d |d | |k }tf ||t|| dd|}|rT|| |d< |rf|| |d	< t|||| f|}|||r|d nd|rdn|d  qW t|d |r|	n|
|r|n|}|	t
||r|| n|d |r|n|||rd
nd| qW n|r(|r(t| ||g}dd |D }| |  }| |  } | |  }!xt|D ]\}"}#xvt| D ]h\}$}%y||#|%f }W n2 tk
r   tjd d d gg|||gd}Y nX x|!D ]}|j d d d ggkr8||| |k }&tf ||t|| dd|}|&| }'|&| }(n2tf ||t|| ddd|}|| }'|| }(|rx|'|d< |r|(|d	< t|||| f|}|||"d |$d  qW |"dkrt| |$ |
|}|	t
||$d ||d|d qW t||" |	|}|	t
|||" ||d
|d qpW ||fS )NTF)rowscolsshared_xaxesshared_yaxeshorizontal_spacingvertical_spacing
print_gridr   )r!   )r?   namerN   r	   r%   r&   r1   r/   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)r?   rZ   rN   
showlegend)r5   r   )r   listgroupbyr   rR   append_trace	enumerateuniquer   rE   r7   KeyErrorpd	DataFramevaluestolist))dfr%   r&   	facet_row	facet_colr-   colormapnum_of_rowsnum_of_colsfacet_row_labelsfacet_col_labelsrP   rG   rH   
show_boxesr4   marker_colorkwargs_tracerQ   rF   annotationsZcolor_groupsgrouprO   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   s    
,


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|}xt|D ]\}}tf |t| | |dtd	d
dd|}|r|d | |d< |r|d | |d< t||| | f|}|||rD|d nd|rPdn|d  |rd|	n|
}t|d ||r||n|}|t	||r|| n|d |r|n|||rdnd|d qW n|r|rt| ||g}dd |D }| | 
 }| | 
 }xt|D ]~\}} x>t|D ]0\}!}"y|| |"f }W n2 tk
r|   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r0t||! |
|}|t	||!d ||d|d q0W t|| |	|}|t	|| || ||d|d qW ||fS )NTF)rS   rT   rU   rV   rW   rX   rY   )r!   
colorscale	showscale)r?   rN   r%   r&   r	   gffffff?)r%   )r!   r   r   Zcolorbarr   r1   r/   )r   c             S   s   i | ]}|d  |d qS )r	   r   r   )r[   r\   r   r   r   r]     s    z/_facet_grid_color_numerical.<locals>.<dictcomp>)r^   )r?   r_   )r5   r   )r   r   rR   rb   r`   ra   rc   r   rE   r7   rd   re   rf   rg   rh   ri   )#rj   r%   r&   rk   rl   r-   rm   rn   ro   rp   rq   rP   rG   rH   rr   r4   rs   rt   rQ   rF   ru   rO   rw   rx   rv   labelsr   ry   rz   r{   r|   r}   r~   r   r   r   r   r   _facet_grid_color_numericalb  s    &

r   c              C   s>  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|}xt|D ]\}}tf |	t||d dd|}|r|d	 | |d< |r
|d	 | |d< t||	|f|}|||r.|d	 nd	|r:d	n|d	  t|d
 |rV|n||rb|n|}|t	||r~|| n|d	 |r|n|||rdnd|
 qW n|r6|r6t| ||g}dd |D }| | 
 }| | 
 }x@t|D ]2\}}xt|D ]\}}y|||f }W n. tk
rX   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W t|| ||}|t	||| ||d|
d qW ||fS )NTF)rS   rT   rU   rV   rW   rX   rY   r>   )r!   r>   )r?   rN   r%   r&   r	   r   r1   r/   c             S   s   i | ]}|d  |d qS )r	   r   r   )r[   r\   r   r   r   r]   W  s    z_facet_grid.<locals>.<dictcomp>)r^   )r5   r   )r   r   rR   rb   r`   ra   rc   r   rE   r7   rd   re   rf   rg   ) rj   r%   r&   rk   rl   rn   ro   rp   rq   rP   rG   rH   rr   r4   rs   rt   rQ   rF   ru   rO   rw   rx   rv   r   ry   rz   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xJ|||||gD ]8}|dk	rVy| |  W qV tk
r   tdY qVX qVW |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rF|sFd|d< d|krn|sfddd|d< ni |d< |s|sd}nd}d}d}d}d}|rt| |  }t|}t|trxD| |  D ]4}|| kr| |   }tt
|qW |rtt| |  }t|}t|	trtxD| |  D ]4}||	 kr<| |   }tt
|q<W d}|rt| | jd ts|rhd}t|trt|d x|| |  D ]}|| krtdqW nLtj} i }d}!x<| |  D ],}|!t| krd}!| |! ||< |!d7 }!qW t| ||||||||||	||||||||\}"}#q t| | jd tr t|trd}t|d x.| |  D ]}|| krtdqW t| ||||||||||	||||||||\}"}#nt|trH|}$t|$ t| ||||||$||||	||||||||\}"}#nt|tr|tj krptj| }$ntd 
tj t| ||||||$||||	||||||||\}"}#n:tjd! }$t| ||||||$||||	||||||||\}"}#n,t| ||||||||	||||||||\}"}#|
s4td"d#| }
|sHtd"d#| }|"d$ j |
|d%d&d' |rx|"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< |rb|rbt'|"t(|| g g d8}(xD|"d$ D ]8}d9|kr|(d+ #| nd:|krv|(d, #| qvW d})xpd;d< ||gD D ]Z}*t| |*  d trx:| |* D ].}+yt)|+ d})W n t*k
r   Y nX qW qW |)rfx6|( D ]*},x"|(|, D ]}-d=|"d$ |- d>< qFW q8W |d?krzd+d,g}.n2|d@krd,g}.n |dAkrd+g}.n|dkrg }.xX|.D ]N},g }/g }0xV|"dB D ]J}1|1|, dk	rt|1|, dkr|/#t+|1|,  |0#t|1|,  qW xd|/kr4|/,d qW xd|0krP|0,d q8W t+|/}2t|0}3t|2tovt|3t}4|4	rt-.|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}5x|(|, D ]}6|5|"d$ |6 dD< d|"d$ |6 dE< d|"d$ |6 dF< |	rd|"d$ |6 dG< dH|"d$ |6 dE< t1|"d$ |6 dI< t2|"d$ |6 dJ< dK|"d$ |6 dI< t3dLdM|"d$ |6 dN< 	qW |,|.krx<|"d$ D ]0}dO
|,|k	r|4	r|2|3g|"d$ | dP< 	qW qW |"S )Qaj  
    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.)r   r   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?rN   r!   r    r
      Zopacityg333333?r>   Zdarkgreyr	   )r!   r=   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   r;   r8   zrgb(251, 251, 251))heightr=   titlepaper_bgcolorzrgb(255, 255, 255)Zclosest)Zplot_bgcolorr   Z	hovermoder%   r&   r_   ZlegendZbgcolorZborderwidthg?topr$      marginrru   )r%   r&   r@   rC   c             S   s   g | ]}|r|qS r   r   )r[   vr   r   r   
<listcomp>Z  s    z%create_facet_grid.<locals>.<listcomp>categoryr?   r   r   r   datag?dtickZticklenZzerolineZ	tickwidth   Z	gridwidthZ	gridcolor   r   )r!   r    Ztickfontz{}axisrange)4rf   ImportErrorr   rg   r   ZPlotlyErrorr   Zvalidate_dataframere   VALID_TRACE_TYPESr   poplenrd   r   r   rD   ri   CUSTOM_LABEL_ERRORZilocr   clrsZvalidate_colors_dictZDEFAULT_PLOTLY_COLORSr   r   r`   Zvalidate_colorscaler   ZPLOTLY_SCALESr   maxupdatePLOT_BGCOLORr:   rE   LEGEND_COLORLEGEND_BORDER_WIDTHr.   rK   ANNOT_RECT_COLORint
ValueErrorminremovemathfloorceilMAX_TICKS_PER_AXIS
GRID_WIDTH
GRID_COLOR
TICK_COLOR)7rj   r%   r&   rk   rl   r-   rm   Zcolor_is_catrp   rq   r   r=   rP   ZscalesZdtick_xZdtick_yrr   Zggplot2ZbinsizekwargsrI   r4   rQ   rs   rt   rn   ro   rG   rH   Zunique_keysZshow_legendvalZdefault_colorsrx   rF   ru   Zcolorscale_listZx_title_annotZy_title_annotZlegend_annotZaxis_labelsZstring_number_in_datavarr\   Zx_yZ	axis_nameZ
fixed_axesZ
min_rangesZ
max_rangesrO   Z	min_rangeZ	max_rangeZrange_are_numbersr   Z
axis_titler   r   r   create_facet_grid  s    






















 




 r   )r/   T)FF)NNNNNNFNNNNr   r   NNTFr	   )+
__future__r   Zplotlyr   r   Zplotly.colorscolorsr   Zplotly.figure_factoryr   Zplotly.subplotsr   r   Znumbersr   Z
get_modulerf   r   r3   r9   r   r   r   r   r   r,   ZLEGEND_ANNOT_Yr   r   r   r   r   r   r   r.   r7   r:   rK   rR   r   r   r   r   r   r   r   r   <module>   sj   


+
$ *                   