Skip to content

remove plotly/colors.py in favour of utils #1279

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 23 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
08e832e
copy n_colors from colors to utils - update all references to colors.…
Kully Nov 20, 2018
0815790
copy good PLOTLY_SCALES in colors.py to incorrect one in utils ; redi…
Kully Nov 20, 2018
30e228e
fix utils.validate_colors so that plotly colors do not give error
Kully Nov 21, 2018
450bcf6
get tests to work
Kully Nov 22, 2018
098bf3d
add invalidd plotly scales back so tests dont break
Kully Nov 22, 2018
ba55531
move nNumbers import to top of utils.py file
Kully Nov 22, 2018
053a9df
copy convert_colors_to_same_type to utils and redirect uses of that f…
Kully Nov 22, 2018
ebab2c4
add utils module to _trisurf.py so previous commit works well
Kully Nov 22, 2018
2e12e5e
copied convert_colorscale_to_rgb to utils.py and switched references …
Kully Nov 22, 2018
ba714ae
copied convert_dict_colors_to_same_type over to utils from colors module
Kully Nov 22, 2018
360256b
make_colorscale now in utils and all references go to it
Kully Nov 22, 2018
85a92d7
rename test_colors to test_figure_factory_utils
Kully Nov 22, 2018
d671498
moved utils test to test_optional folder
Kully Nov 22, 2018
51d679d
remove colors.py
Kully Nov 23, 2018
8e18756
safely remove colors imports
Kully Nov 23, 2018
6df3de5
all functions in figure_factory.utils.py are tested in test_optional
Kully Nov 23, 2018
768c161
remove commented out test
Kully Nov 23, 2018
9f765b9
add colors.py back
Kully Nov 29, 2018
30cbcdd
only import public variables and methods into plotly.colors
Kully Nov 29, 2018
b6c61c1
move from __future__... import at top of file
Kully Nov 29, 2018
fe26750
correct relative path for utils reference
Kully Nov 29, 2018
22c7599
rebase back to 'remove commented out test' commit where the only work…
Kully Dec 10, 2018
dc81ca2
reverted now to ''make_colorscale now in utils and all references go …
Kully Dec 10, 2018
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions plotly/figure_factory/_bullet.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def _bullet(df, markers, measures, ranges, subtitles, titles, orientation,
for row in range(num_of_lanes):
# ranges bars
for idx in range(len(df.iloc[row]['ranges'])):
inter_colors = colors.n_colors(
inter_colors = utils.n_colors(
range_colors[0], range_colors[1],
len(df.iloc[row]['ranges']), 'rgb'
)
Expand All @@ -104,7 +104,7 @@ def _bullet(df, markers, measures, ranges, subtitles, titles, orientation,

# measures bars
for idx in range(len(df.iloc[row]['measures'])):
inter_colors = colors.n_colors(
inter_colors = utils.n_colors(
measure_colors[0], measure_colors[1],
len(df.iloc[row]['measures']), 'rgb'
)
Expand Down Expand Up @@ -318,7 +318,7 @@ def create_bullet(data, markers=None, measures=None, ranges=None,
"of two valid colors."
)
colors.validate_colors(colors_list)
colors_list = colors.convert_colors_to_same_type(colors_list,
colors_list = utils.convert_colors_to_same_type(colors_list,
'rgb')[0]

# default scatter options
Expand Down
4 changes: 2 additions & 2 deletions plotly/figure_factory/_county_choropleth.py
Original file line number Diff line number Diff line change
Expand Up @@ -642,7 +642,7 @@ def create_choropleth(fips, values, scope=['usa'], binning_endpoints=None,
if not colorscale:
colorscale = []
viridis_colors = colors.colorscale_to_colors(
colors.PLOTLY_SCALES['Viridis']
utils.PLOTLY_SCALES['Viridis']
)
viridis_colors = colors.color_parser(
viridis_colors, colors.hex_to_rgb
Expand Down Expand Up @@ -674,7 +674,7 @@ def create_choropleth(fips, values, scope=['usa'], binning_endpoints=None,

# make R,G,B into int values
float_color = colors.unlabel_rgb(float_color)
float_color = colors.unconvert_from_RGB_255(float_color)
float_color = utils.unconvert_from_RGB_255(float_color)
int_rgb = colors.convert_to_RGB_255(float_color)
int_rgb = colors.label_rgb(int_rgb)

Expand Down
8 changes: 4 additions & 4 deletions plotly/figure_factory/_facet_grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -935,13 +935,13 @@ def create_facet_grid(df, x=None, y=None, facet_row=None, facet_col=None,
marker_color, kwargs_trace, kwargs_marker
)
elif isinstance(colormap, str):
if colormap in colors.PLOTLY_SCALES.keys():
colorscale_list = colors.PLOTLY_SCALES[colormap]
if colormap in utils.PLOTLY_SCALES.keys():
colorscale_list = utils.PLOTLY_SCALES[colormap]
else:
raise exceptions.PlotlyError(
"If 'colormap' is a string, it must be the name "
"of a Plotly Colorscale. The available colorscale "
"names are {}".format(colors.PLOTLY_SCALES.keys())
"names are {}".format(utils.PLOTLY_SCALES.keys())
)
fig, annotations = _facet_grid_color_numerical(
df, x, y, facet_row, facet_col, color_name,
Expand All @@ -951,7 +951,7 @@ def create_facet_grid(df, x=None, y=None, facet_row=None, facet_col=None,
marker_color, kwargs_trace, kwargs_marker
)
else:
colorscale_list = colors.PLOTLY_SCALES['Reds']
colorscale_list = utils.PLOTLY_SCALES['Reds']
fig, annotations = _facet_grid_color_numerical(
df, x, y, facet_row, facet_col, color_name,
colorscale_list, num_of_rows, num_of_cols,
Expand Down
15 changes: 15 additions & 0 deletions plotly/figure_factory/_scatterplot.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import absolute_import

import six

from plotly import colors, exceptions, optional_imports
from plotly.figure_factory import utils
from plotly.graph_objs import graph_objs
Expand Down Expand Up @@ -1080,6 +1082,19 @@ def create_scatterplotmatrix(df, index=None, endpts=None, diag='scatter',
# Validate colormap
if isinstance(colormap, dict):
colormap = utils.validate_colors_dict(colormap, 'rgb')
elif isinstance(colormap, six.string_types) and 'rgb' not in colormap and '#' not in colormap:
if colormap not in utils.PLOTLY_SCALES.keys():
raise exceptions.PlotlyError(
"If 'colormap' is a string, it must be the name "
"of a Plotly Colorscale. The available colorscale "
"names are {}".format(utils.PLOTLY_SCALES.keys())
)
else:
# TODO change below to allow the correct Plotly colorscale
colormap = utils.colorscale_to_colors(utils.PLOTLY_SCALES[colormap])
# keep only first and last item - fix later
colormap = [colormap[0]] + [colormap[-1]]
colormap = utils.validate_colors(colormap, 'rgb')
else:
colormap = utils.validate_colors(colormap, 'rgb')

Expand Down
7 changes: 4 additions & 3 deletions plotly/figure_factory/_trisurf.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import absolute_import

from plotly import colors, exceptions, optional_imports
from plotly.figure_factory import utils
from plotly.graph_objs import graph_objs

np = optional_imports.get_module('numpy')
Expand Down Expand Up @@ -147,8 +148,8 @@ def trisurf(x, y, z, simplices, show_colorbar, edges_color, scale,

if mean_dists_are_numbers and show_colorbar is True:
# make a colorscale from the colors
colorscale = colors.make_colorscale(colormap, scale)
colorscale = colors.convert_colorscale_to_rgb(colorscale)
colorscale = utils.make_colorscale(colormap, scale)
colorscale = utils.convert_colorscale_to_rgb(colorscale)

colorbar = graph_objs.Scatter3d(
x=x[:1],
Expand Down Expand Up @@ -455,7 +456,7 @@ def dist_origin(x, y, z):

# Validate colormap
colors.validate_colors(colormap)
colormap, scale = colors.convert_colors_to_same_type(
colormap, scale = utils.convert_colors_to_same_type(
colormap, colortype='tuple',
return_default_colors=True, scale=scale
)
Expand Down
166 changes: 166 additions & 0 deletions plotly/figure_factory/figure_factory/_2d_density.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
from __future__ import absolute_import

from numbers import Number

from plotly import exceptions
from plotly.figure_factory import utils
from plotly.graph_objs import graph_objs


def make_linear_colorscale(colors):
"""
Makes a list of colors into a colorscale-acceptable form

For documentation regarding to the form of the output, see
https://plot.ly/python/reference/#mesh3d-colorscale
"""
scale = 1. / (len(colors) - 1)
return [[i * scale, color] for i, color in enumerate(colors)]


def create_2d_density(x, y, colorscale='Earth', ncontours=20,
hist_color=(0, 0, 0.5), point_color=(0, 0, 0.5),
point_size=2, title='2D Density Plot',
height=600, width=600):
"""
Returns figure for a 2D density plot

:param (list|array) x: x-axis data for plot generation
:param (list|array) y: y-axis data for plot generation
:param (str|tuple|list) colorscale: either a plotly scale name, an rgb
or hex color, a color tuple or a list or tuple of colors. An rgb
color is of the form 'rgb(x, y, z)' where x, y, z belong to the
interval [0, 255] and a color tuple is a tuple of the form
(a, b, c) where a, b and c belong to [0, 1]. If colormap is a
list, it must contain the valid color types aforementioned as its
members.
:param (int) ncontours: the number of 2D contours to draw on the plot
:param (str) hist_color: the color of the plotted histograms
:param (str) point_color: the color of the scatter points
:param (str) point_size: the color of the scatter points
:param (str) title: set the title for the plot
:param (float) height: the height of the chart
:param (float) width: the width of the chart

Example 1: Simple 2D Density Plot
```
import plotly.plotly as py
from plotly.figure_factory create_2d_density

import numpy as np

# Make data points
t = np.linspace(-1,1.2,2000)
x = (t**3)+(0.3*np.random.randn(2000))
y = (t**6)+(0.3*np.random.randn(2000))

# Create a figure
fig = create_2D_density(x, y)

# Plot the data
py.iplot(fig, filename='simple-2d-density')
```

Example 2: Using Parameters
```
import plotly.plotly as py
from plotly.figure_factory create_2d_density

import numpy as np

# Make data points
t = np.linspace(-1,1.2,2000)
x = (t**3)+(0.3*np.random.randn(2000))
y = (t**6)+(0.3*np.random.randn(2000))

# Create custom colorscale
colorscale = ['#7A4579', '#D56073', 'rgb(236,158,105)',
(1, 1, 0.2), (0.98,0.98,0.98)]

# Create a figure
fig = create_2D_density(
x, y, colorscale=colorscale,
hist_color='rgb(255, 237, 222)', point_size=3)

# Plot the data
py.iplot(fig, filename='use-parameters')
```
"""

# validate x and y are filled with numbers only
for array in [x, y]:
if not all(isinstance(element, Number) for element in array):
raise exceptions.PlotlyError(
"All elements of your 'x' and 'y' lists must be numbers."
)

# validate x and y are the same length
if len(x) != len(y):
raise exceptions.PlotlyError(
"Both lists 'x' and 'y' must be the same length."
)

colorscale = utils.validate_colors(colorscale, 'rgb')
colorscale = make_linear_colorscale(colorscale)

# validate hist_color and point_color
hist_color = utils.validate_colors(hist_color, 'rgb')
point_color = utils.validate_colors(point_color, 'rgb')

trace1 = graph_objs.Scatter(
x=x, y=y, mode='markers', name='points',
marker=dict(
color=point_color[0],
size=point_size,
opacity=0.4
)
)
trace2 = graph_objs.Histogram2dContour(
x=x, y=y, name='density', ncontours=ncontours,
colorscale=colorscale, reversescale=True, showscale=False
)
trace3 = graph_objs.Histogram(
x=x, name='x density',
marker=dict(color=hist_color[0]), yaxis='y2'
)
trace4 = graph_objs.Histogram(
y=y, name='y density',
marker=dict(color=hist_color[0]), xaxis='x2'
)
data = [trace1, trace2, trace3, trace4]

layout = graph_objs.Layout(
showlegend=False,
autosize=False,
title=title,
height=height,
width=width,
xaxis=dict(
domain=[0, 0.85],
showgrid=False,
zeroline=False
),
yaxis=dict(
domain=[0, 0.85],
showgrid=False,
zeroline=False
),
margin=dict(
t=50
),
hovermode='closest',
bargap=0,
xaxis2=dict(
domain=[0.85, 1],
showgrid=False,
zeroline=False
),
yaxis2=dict(
domain=[0.85, 1],
showgrid=False,
zeroline=False
)
)

fig = graph_objs.Figure(data=data, layout=layout)
return fig
24 changes: 24 additions & 0 deletions plotly/figure_factory/figure_factory/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from __future__ import absolute_import

from plotly import optional_imports

# Require that numpy exists for figure_factory
import numpy

from plotly.figure_factory._2d_density import create_2d_density
from plotly.figure_factory._annotated_heatmap import create_annotated_heatmap
from plotly.figure_factory._bullet import create_bullet
from plotly.figure_factory._candlestick import create_candlestick
from plotly.figure_factory._dendrogram import create_dendrogram
from plotly.figure_factory._distplot import create_distplot
from plotly.figure_factory._facet_grid import create_facet_grid
from plotly.figure_factory._gantt import create_gantt
from plotly.figure_factory._ohlc import create_ohlc
from plotly.figure_factory._quiver import create_quiver
from plotly.figure_factory._scatterplot import create_scatterplotmatrix
from plotly.figure_factory._streamline import create_streamline
from plotly.figure_factory._table import create_table
from plotly.figure_factory._trisurf import create_trisurf
from plotly.figure_factory._violin import create_violin
if optional_imports.get_module('pandas') is not None:
from plotly.figure_factory._county_choropleth import create_choropleth
Loading