Plotly error: Invalid 'figure_or_data' argument - python

an animation example from this plotly tutorial is not working with Plotly 2.0.12. I put the error output below. Is there any way to solve the problem? I am using plotly on a Jupyter Notebook.
PlotlyError: Invalid 'figure_or_data' argument. Plotly will not be
able to properly parse the resulting JSON. If you want to send this
'figure_or_data' to Plotly anyway (not recommended), you can set
'validate=False' as a plot option.
Here's why you're seeing this error:
'slider' is not allowed in 'layout'
Path To Error: ['layout']['slider']
Valid attributes for 'layout' at path ['layout'] under parents
['figure']:
['angularaxis', 'annotations', 'autosize', 'bargap', 'bargroupgap',
'barmode', 'barnorm', 'boxgap', 'boxgroupgap', 'boxmode', 'calendar',
'direction', 'dragmode', 'font', 'geo', 'height', 'hiddenlabels',
'hiddenlabelssrc', 'hidesources', 'hoverlabel', 'hovermode',
'images',
'legend', 'mapbox', 'margin', 'orientation', 'paper_bgcolor',
'plot_bgcolor', 'radialaxis', 'scene', 'separators', 'shapes',
'showlegend', 'sliders', 'smith', 'ternary', 'title', 'titlefont',
'updatemenus', 'width', 'xaxis', 'yaxis']
Run `<layout-object>.help('attribute')` on any of the above.
'<layout-object>' is the object at ['layout']
EDIT: Just noticed the link is broken. Here is the full code:
from plotly.offline import init_notebook_mode, iplot
from IPython.display import display, HTML
import pandas as pd
init_notebook_mode(connected=True)
url = 'https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv'
dataset = pd.read_csv(url)
years = ['1952', '1962', '1967', '1972', '1977', '1982', '1987', '1992', '1997', '2002', '2007']
# make list of continents
continents = []
for continent in dataset['continent']:
if continent not in continents:
continents.append(continent)
# make figure
figure = {
'data': [],
'layout': {},
'frames': [],
'config': {'scrollzoom': True}
}
# fill in most of layout
figure['layout']['xaxis'] = {'range': [30, 85], 'title': 'Life Expectancy'}
figure['layout']['yaxis'] = {'title': 'GDP per Capita', 'type': 'log'}
figure['layout']['hovermode'] = 'closest'
figure['layout']['slider'] = {
'args': [
'slider.value', {
'duration': 400,
'ease': 'cubic-in-out'
}
],
'initialValue': '1952',
'plotlycommand': 'animate',
'values': years,
'visible': True
}
figure['layout']['updatemenus'] = [
{
'buttons': [
{
'args': [None, {'frame': {'duration': 500, 'redraw': False},
'fromcurrent': True, 'transition': {'duration': 300, 'easing': 'quadratic-in-out'}}],
'label': 'Play',
'method': 'animate'
},
{
'args': [[None], {'frame': {'duration': 0, 'redraw': False}, 'mode': 'immediate',
'transition': {'duration': 0}}],
'label': 'Pause',
'method': 'animate'
}
],
'direction': 'left',
'pad': {'r': 10, 't': 87},
'showactive': False,
'type': 'buttons',
'x': 0.1,
'xanchor': 'right',
'y': 0,
'yanchor': 'top'
}
]
sliders_dict = {
'active': 0,
'yanchor': 'top',
'xanchor': 'left',
'currentvalue': {
'font': {'size': 20},
'prefix': 'Year:',
'visible': True,
'xanchor': 'right'
},
'transition': {'duration': 300, 'easing': 'cubic-in-out'},
'pad': {'b': 10, 't': 50},
'len': 0.9,
'x': 0.1,
'y': 0,
'steps': []
}
# make data
year = 1952
for continent in continents:
dataset_by_year = dataset[dataset['year'] == year]
dataset_by_year_and_cont =
dataset_by_year[dataset_by_year['continent'] == continent]
data_dict = {
'x': list(dataset_by_year_and_cont['lifeExp']),
'y': list(dataset_by_year_and_cont['gdpPercap']),
'mode': 'markers',
'text': list(dataset_by_year_and_cont['country']),
'marker': {
'sizemode': 'area',
'sizeref': 200000,
'size': list(dataset_by_year_and_cont['pop'])
},
'name': continent
}
figure['data'].append(data_dict)
# make frames
for year in years:
frame = {'data': [], 'name': str(year)}
for continent in continents:
dataset_by_year = dataset[dataset['year'] == int(year)]
dataset_by_year_and_cont =
dataset_by_year[dataset_by_year['continent'] == continent]
data_dict = {
'x': list(dataset_by_year_and_cont['lifeExp']),
'y': list(dataset_by_year_and_cont['gdpPercap']),
'mode': 'markers',
'text': list(dataset_by_year_and_cont['country']),
'marker': {
'sizemode': 'area',
'sizeref': 200000,
'size': list(dataset_by_year_and_cont['pop'])
},
'name': continent
}
frame['data'].append(data_dict)
figure['frames'].append(frame)
slider_step = {'args': [
[year],
{'frame': {'duration': 300, 'redraw': False},
'mode': 'immediate',
'transition': {'duration': 300}}
],
'label': year,
'method': 'animate'}
sliders_dict['steps'].append(slider_step)
figure['layout']['sliders'] = [sliders_dict]
iplot(figure)
I do not know if I have to downgrade the version (and, in case, to which one) but I'd rather not.

I validated your code and found some errors.
On Line 29 you should have given
figure['layout']['sliders'] instead of figure['layout']['slider']
Plotly offline's iplot function has a separate parameter of inputting config of the plot.
So the below line
# make figure
figure = {
'data': [],
'layout': {},
'frames': [],
'config': {'scrollzoom': True}
}
and the line
iplot(figure)
should actually be written as
# make figure
figure = {
'data': [],
'layout': {},
'frames': []
}
config = {'scrollzoom': True}
and
iplot(figure, config=config)
So the final working code should be
from plotly.offline import init_notebook_mode, iplot
from IPython.display import display, HTML
import pandas as pd
init_notebook_mode(connected=True)
url = 'https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv'
dataset = pd.read_csv(url)
years = ['1952', '1962', '1967', '1972', '1977', '1982', '1987', '1992', '1997', '2002', '2007']
# make list of continents
continents = []
for continent in dataset['continent']:
if continent not in continents:
continents.append(continent)
# make figure
figure = {
'data': [],
'layout': {},
'frames': []
}
config = {'scrollzoom': True}
# fill in most of layout
figure['layout']['xaxis'] = {'range': [30, 85], 'title': 'Life Expectancy'}
figure['layout']['yaxis'] = {'title': 'GDP per Capita', 'type': 'log'}
figure['layout']['hovermode'] = 'closest'
figure['layout']['sliders'] = {
'args': [
'slider.value', {
'duration': 400,
'ease': 'cubic-in-out'
}
],
'initialValue': '1952',
'plotlycommand': 'animate',
'values': years,
'visible': True
}
figure['layout']['updatemenus'] = [
{
'buttons': [
{
'args': [None, {'frame': {'duration': 500, 'redraw': False},
'fromcurrent': True, 'transition': {'duration': 300, 'easing': 'quadratic-in-out'}}],
'label': 'Play',
'method': 'animate'
},
{
'args': [[None], {'frame': {'duration': 0, 'redraw': False}, 'mode': 'immediate',
'transition': {'duration': 0}}],
'label': 'Pause',
'method': 'animate'
}
],
'direction': 'left',
'pad': {'r': 10, 't': 87},
'showactive': False,
'type': 'buttons',
'x': 0.1,
'xanchor': 'right',
'y': 0,
'yanchor': 'top'
}
]
sliders_dict = {
'active': 0,
'yanchor': 'top',
'xanchor': 'left',
'currentvalue': {
'font': {'size': 20},
'prefix': 'Year:',
'visible': True,
'xanchor': 'right'
},
'transition': {'duration': 300, 'easing': 'cubic-in-out'},
'pad': {'b': 10, 't': 50},
'len': 0.9,
'x': 0.1,
'y': 0,
'steps': []
}
# make data
year = 1952
for continent in continents:
dataset_by_year = dataset[dataset['year'] == year]
dataset_by_year_and_cont=dataset_by_year[dataset_by_year['continent'] == continent]
data_dict = {
'x': list(dataset_by_year_and_cont['lifeExp']),
'y': list(dataset_by_year_and_cont['gdpPercap']),
'mode': 'markers',
'text': list(dataset_by_year_and_cont['country']),
'marker': {
'sizemode': 'area',
'sizeref': 200000,
'size': list(dataset_by_year_and_cont['pop'])
},
'name': continent
}
figure['data'].append(data_dict)
# make frames
for year in years:
frame = {'data': [], 'name': str(year)}
for continent in continents:
dataset_by_year = dataset[dataset['year'] == int(year)]
dataset_by_year_and_cont=dataset_by_year[dataset_by_year['continent'] == continent]
data_dict = {
'x': list(dataset_by_year_and_cont['lifeExp']),
'y': list(dataset_by_year_and_cont['gdpPercap']),
'mode': 'markers',
'text': list(dataset_by_year_and_cont['country']),
'marker': {
'sizemode': 'area',
'sizeref': 200000,
'size': list(dataset_by_year_and_cont['pop'])
},
'name': continent
}
frame['data'].append(data_dict)
figure['frames'].append(frame)
slider_step = {'args': [
[year],
{'frame': {'duration': 300, 'redraw': False},
'mode': 'immediate',
'transition': {'duration': 300}}
],
'label': year,
'method': 'animate'}
sliders_dict['steps'].append(slider_step)
figure['layout']['sliders'] = [sliders_dict]
iplot(figure, config=config)
I hope this helps you resolve your issue, the slider looks great :)

Related

Using dash_cytoscape line-gradient-stop-colors

I am attempting to create gradients within the edges of a graph in dash_cytoscape using line-gradient-stop-colors (from the js.cytoscape documentation). I am doing this with a stylesheet that describes a gradient layout for all of the edges in my graph. Example code is below, however it creates a graph with just grey edges.
import dash
import dash_cytoscape as cyto
from dash import html
app = dash.Dash(__name__)
style_1 = [
{
'selector': 'node',
'style': {
'label': 'data(id)',
'background-color': 'blue',
}
},
{
'selector': 'edge',
'style': {
'line-gradient-stop-colors': 'cyan magenta yellow', # these are the lines that I have issue with
'line-gradient-stop-positions': '25 50 75',
}
}
]
app.layout = html.Div([
cyto.Cytoscape(
id='cytoscape-elements-boolean',
layout={'name': 'preset'},
style={'width': '100%', 'height': '800px'},
stylesheet=style_1,
elements=[
{
'data': {'id': 'one'},
'position': {'x': 75, 'y': 75},
},
{
'data': {'id': 'two'},
'position': {'x': 75, 'y': 200},
},
{
'data': {'id': 'three'},
'position': {'x': 200, 'y': 75},
},
{
'data': {'id': 'four'},
'position': {'x': 200, 'y': 200}
},
{'data': {'source': 'one', 'target': 'two'}},
{'data': {'source': 'two', 'target': 'three'}},
{'data': {'source': 'three', 'target': 'four'}},
{'data': {'source': 'two', 'target': 'four'}},
]
)
])
if __name__ == '__main__':
app.run_server(debug=True)
I believe the issue is how I have the line-gradient-stop-colors string set up but I've tried multiple options and none of them have worked. Any help would be greatly appreciated!

Dynamic add list in to json-dict as float

Im running a python 3.7 script where im trying to remove quotes.
Im trying to add a dynamic list (x and y coordinates) to a json-dictionary but i keep getting quotes surrounding the list. I need the list to be inserted without these quotes.
Here is my code that im running:
#The dynamic list
polygon = ['0.124912491249125', '0.683368336833683', '0.128112811281128', '0.472147214721472', '-0.096909690969097', '0.444344434443444', '-0.196919691969197', '-0.533353335333533', '-0.64996499649965', '-0.427742774277428', '-0.290529052905291', '-0.266726672667267', '-0.237523752375237', '0.64996499649965']
list_polygon = []
for i,k in zip(polygon[0::2], polygon[1::2]):
data_polygon = ('['+str(i), str(k)+']')
data_polygon = str(data_polygon)
list_polygon.append(data_polygon)
list_polygon = str(list_polygon)
list_polygon = list_polygon.replace("'",'').replace("(",'').replace(")",'').replace("[[",'[').replace("]]",']')
cord_data = {'apiVersion': '1.3',
'context': '<client context>',
'params': {'cameras': [{'active': True, 'id': 1, 'rotation': 0}],
'configurationStatus': 5,
'profiles': [{'camera': 1,
'filters': [{'active': True,
'data': 1,
'type': 'timeShortLivedLimit'},
{'active': True,
'data': 5,
'type': 'distanceSwayingObject'},
{'active': True,
'data': [5, 5],
'type': 'sizePercentage'}],
'name': 'Profile 1',
'triggers': [{'data': [list_polygon],
'type': 'includeArea'}],
'uid': 1}]},
'method': 'setConfiguration'}
And i get the answer:
{'apiVersion': '1.3', 'context': '<client context>', 'params': {'cameras': [{'active': True, 'id': 1, 'rotation': 0}], 'configurationStatus': 5, 'profiles': [{'camera': 1, 'filters': [{'active': True, 'data': 1, 'type': 'timeShortLivedLimit'}, {'active': True, 'data': 5, 'type': 'distanceSwayingObject'}, {'active': True, 'data': [5, 5], 'type': 'sizePercentage'}], 'name': 'Profile 1', 'triggers': [{'data': ['[0.124912491249125, 0.683368336833683], [0.128112811281128, 0.472147214721472], [-0.096909690969097, 0.444344434443444], [-0.196919691969197, -0.533353335333533], [-0.64996499649965, -0.427742774277428], [-0.290529052905291, -0.266726672667267], [-0.237523752375237, 0.64996499649965]'], 'type': 'includeArea'}], 'uid': 1}]}, 'method': 'setConfiguration'}
As you see it adds a quote between the brackets (at the start and the end) 'triggers': [{'data': ['[ 0.124912491249125, 0.683368336833683], [0.128112811281128, 0.472147214721472], [-0.096909690969097, 0.444344434443444], [-0.196919691969197, -0.533353335333533], [-0.64996499649965, -0.427742774277428], [-0.290529052905291, -0.266726672667267], [-0.237523752375237, 0.64996499649965 ]']
Instead i want it to look like this:
'triggers': [{'data': [[ 0.124912491249125, 0.683368336833683], [0.128112811281128, 0.472147214721472], [-0.096909690969097, 0.444344434443444], [-0.196919691969197, -0.533353335333533], [-0.64996499649965, -0.427742774277428], [-0.290529052905291, -0.266726672667267], [-0.237523752375237, 0.64996499649965 ]]
The first and second must be paired.
The post i want to send should look like this:
cord_data = {'apiVersion': '1.3',
'context': '<client context>',
'params': {'cameras': [{'active': True, 'id': 1, 'rotation': 0}],
'configurationStatus': 5,
'profiles': [{'camera': 1,
'filters': [{'active': True,
'data': 1,
'type': 'timeShortLivedLimit'},
{'active': True,
'data': 5,
'type': 'distanceSwayingObject'},
{'active': True,
'data': [5, 5],
'type': 'sizePercentage'}],
'name': 'Profile 1',
'triggers': [{'data': [[0.124912491249125, 0.683368336833683],
[0.128112811281128, 0.472147214721472],
[-0.096909690969097, 0.444344434443444]
and so on],
'type': 'includeArea'}],
'uid': 1}]},
'method': 'setConfiguration'}
What im i doing wrong?
You make every effort to make it str first, when you need list of lists of floats.
polygon = ['0.124912491249125', '0.683368336833683', '0.128112811281128', '0.472147214721472', '-0.096909690969097', '0.444344434443444', '-0.196919691969197', '-0.533353335333533', '-0.64996499649965', '-0.427742774277428', '-0.290529052905291', '-0.266726672667267', '-0.237523752375237', '0.64996499649965']
list_polygon = [[float(i), float(k)] for i,k in zip(polygon[0::2], polygon[1::2])]
cord_data = {'apiVersion': '1.3',
'context': '<client context>',
'params': {'cameras': [{'active': True, 'id': 1, 'rotation': 0}],
'configurationStatus': 5,
'profiles': [{'camera': 1,
'filters': [{'active': True,
'data': 1,
'type': 'timeShortLivedLimit'},
{'active': True,
'data': 5,
'type': 'distanceSwayingObject'},
{'active': True,
'data': [5, 5],
'type': 'sizePercentage'}],
'name': 'Profile 1',
'triggers': [{'data': list_polygon,
'type': 'includeArea'}],
'uid': 1}]},
'method': 'setConfiguration'}
print(cord_data)
And a word of advise - don't forget Floating Point Arithmetic: Issues and Limitations
I guess you'd want something like this:
from pprint import pprint
#The dynamic list
polygon = ['0.124912491249125', '0.683368336833683', '0.128112811281128', '0.472147214721472', '-0.096909690969097', '0.444344434443444', '-0.196919691969197', '-0.533353335333533', '-0.64996499649965', '-0.427742774277428', '-0.290529052905291', '-0.266726672667267', '-0.237523752375237', '0.64996499649965']
list_polygon = []
for i,k in zip(polygon[0::2], polygon[1::2]):
# Don't duplicate convert to `str`, please. Data is already a string.
data_polygon = ([i, k])
# Remove this line, it messes it up if retained
# data_polygon = str(data_polygon)
list_polygon.append(data_polygon)
# Why are we converting all lists to string anyway??
# list_polygon = str(list_polygon)
# list_polygon = list_polygon.replace("'",'').replace("(",'').replace(")",'').replace("[[",'[').replace("]]",']')
# Convert all nested strings to floats
list_polygon = [list(map(float, data_polygon)) for data_polygon in list_polygon]
cord_data = {'apiVersion': '1.3',
'context': '<client context>',
'params': {'cameras': [{'active': True, 'id': 1, 'rotation': 0}],
'configurationStatus': 5,
'profiles': [{'camera': 1,
'filters': [{'active': True,
'data': 1,
'type': 'timeShortLivedLimit'},
{'active': True,
'data': 5,
'type': 'distanceSwayingObject'},
{'active': True,
'data': [5, 5],
'type': 'sizePercentage'}],
'name': 'Profile 1',
# Don't nest it within another list (unless needed)
# 'triggers': [{'data': [list_polygon],
'triggers': [{'data': list_polygon,
'type': 'includeArea'}],
'uid': 1}]},
'method': 'setConfiguration'}
pprint(cord_data)

How do I turn my JSON into something easier to read?

My Python script connects to an API and gets some JSON.
I've been trying out prettyprint, parse, loads, dumps but I haven't figured them out yet...
Right now, when i do print(request.json()) I get this:
{'info': {'status': 'OK', 'time': {'seconds': 0.050006151199341, 'human': '50 milliseconds'}},
'datalist': {'total': 1, 'count': 1, 'offset': 0, 'limit': 3, 'next': 1, 'hidden': 0, 'loaded': True, 'list': [
{'id': 27862209, 'name': 'Fate/Grand Order', 'package': 'com.xiaomeng.fategrandorder',
'uname': 'komoe-game-fate-go', 'size': 49527668,
'icon': 'http://pool.img.xxxxx.com/msi8/9b58a48638b480c17135a10810374bd6_icon.png',
'graphic': 'http://pool.img.xxxxx.com/msi8/3a240b50ac37a9824b9ac99f1daab8c8_fgraphic_705x345.jpg',
'added': '2017-05-20 10:54:53', 'modified': '2017-05-20 10:54:53', 'updated': '2018-02-12 12:35:51',
'uptype': 'regular', 'store': {'id': 750918, 'name': 'msi8',
'avatar': 'http://pool.img.xxxxx.com/msi8/c61a8cfe9f68bfcfb71ef59b46a8ae5d_ravatar.png',
'appearance': {'theme': 'grey',
'description': '❤️ Welcome To Msi8 Store & My Store Will Mostly Be Specialized in Games With OBB File Extension. I Hope You Find What You Are Looking For Here ❤️'},
'stats': {'apps': 20776, 'subscribers': 96868, 'downloads': 25958359}},
'file': {'vername': '1.14.5', 'vercode': 52, 'md5sum': 'xxxxx', 'filesize': 49527668,
'path': 'http://pool.apk.xxxxx.com/msi8/com-xiaomeng-fategrandorder-52-27862209-32a264b031d6933514970c43dea4191f.apk',
'path_alt': 'http://pool.apk.xxxxx.com/msi8/alt/Y29tLXhpYW9tZW5nLWZhdGVncmFuZG9yZGVyLTUyLTI3ODYyMjA5LTMyYTI2NGIwMzFkNjkzMzUxNDk3MGM0M2RlYTQxOTFm.apk',
'malware': {'rank': 'UNKNOWN'}},
'stats': {'downloads': 432, 'pdownloads': 452, 'rating': {'avg': 0, 'total': 0},
'prating': {'avg': 0, 'total': 0}}, 'has_versions': False, 'obb': None,
'xxxxx': {'advertising': False, 'billing': False}}]}}
But I want it to look like this:
>>> import json
>>> a={"some":"json", "a":{"b":[1,2,3,4]}}
>>> print(json.dumps(a, indent=4, sort_keys=True))
{
"a": {
"b": [
1,
2,
3,
4
]
},
"some": "json"
}

Plotly animated slider in Python

I was trying to recreate this example in a Jupyter notebook.
https://plot.ly/python/gapminder-example/
but was getting this error:
PlotlyDictKeyError: 'slider' is not allowed in 'layout'
Path To Error: ['layout']['slider']
Valid attributes for 'layout' at path ['layout'] under parents ['figure']:
['angularaxis', 'annotations', 'autosize', 'bargap', 'bargroupgap',
'barmode', 'barnorm', 'boxgap', 'boxgroupgap', 'boxmode', 'calendar',
'direction', 'dragmode', 'font', 'geo', 'height', 'hiddenlabels',
'hiddenlabelssrc', 'hidesources', 'hoverlabel', 'hovermode', 'images',
'legend', 'mapbox', 'margin', 'orientation', 'paper_bgcolor',
'plot_bgcolor', 'radialaxis', 'scene', 'separators', 'shapes',
'showlegend', 'sliders', 'smith', 'ternary', 'title', 'titlefont',
'updatemenus', 'width', 'xaxis', 'yaxis']
Run `<layout-object>.help('attribute')` on any of the above.
'<layout-object>' is the object at ['layout']
The animation runs without the slider dict added to layout and the slider is visible and operational, but does not change the graph. When I move the slider it produces the following error in the console:
Uncaught (in promise) undefined
Update:
I checked the graph you have, I am observing the below error sometimes.
Uncaught (in promise) undefined
This error might by due to plotly missing an click or other event, but this is internally within the plotly.js file, if you go to Plotly Slider animation link and to the slider animation section, click play and click on the slider while play is running we get this error, even when I click on pause I get this error. But the animation keeps on playing if I press the play again, hence there is no major impact! It's just that an event is not handled properly.
So as in the case of the graph you provided, I can get the animation working fine, eventhough I get the error (Uncaught (in promise) undefined) I am still able to play the animation!
You can use either iplot(fig, validate=False) or plot(fig) to show the graphs in Python with the animation!
Answer:
The error is because the layout object has a property called sliders not slider, so wherever you are using slider under layout, please change this, also this plot is very complicated and may have other errors also, please share the code, for debugging. But for now this will be my answer.
Before:
['layout']['slider']
After:
['layout']['sliders']
Please replace all the slider properties that are related to layout, these need to be changed to sliders.
References:
I have handled issues related to this particular slider animated Plotly graph. Please refer to them if need, they may help solve your issue!
Plotly Animated Bubble Chart No Data in the Plot
Plotly Error Invalid Figure or Data Argument
Plotly Icreate Animations Offline on Jupyter Notebook
You are probably hitting this error because of a typo in that notebook. It should be sliders instead of slider, see the docs.
The other error too, seems to be caused by this typo. It seems that this code is in an event handler that gets triggered whenever you move the slider.
So below line (and similar ones):
figure['layout']['slider']
should be corrected to:
figure['layout']['sliders']
Here is the code for that example:
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.grid_objs import Grid, Column
from plotly.tools import FigureFactory as FF
import pandas as pd
import time
url = 'https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv'
dataset = pd.read_csv(url)
table = FF.create_table(dataset.head(10))
py.iplot(table, filename='animations-gapminder-data-preview')
years_from_col = set(dataset['year'])
years_ints = sorted(list(years_from_col))
years = [str(year) for year in years_ints]
years.remove('1957')
# make list of continents
continents = []
for continent in dataset['continent']:
if continent not in continents:
continents.append(continent)
columns = []
# make grid
for year in years:
for continent in continents:
dataset_by_year = dataset[dataset['year'] == int(year)]
dataset_by_year_and_cont = dataset_by_year[dataset_by_year['continent'] == continent]
for col_name in dataset_by_year_and_cont:
# each column name is unique
column_name = '{year}_{continent}_{header}_gapminder_grid'.format(
year=year, continent=continent, header=col_name
)
a_column = Column(list(dataset_by_year_and_cont[col_name]), column_name)
columns.append(a_column)
# upload grid
grid = Grid(columns)
url = py.grid_ops.upload(grid, 'gapminder_grid'+str(time.time()), auto_open=False)
figure = {
'data': [],
'layout': {},
'frames': [],
'config': {'scrollzoom': True}
}
# fill in most of layout
figure['layout']['xaxis'] = {'range': [30, 85], 'title': 'Life Expectancy', 'gridcolor': '#FFFFFF'}
figure['layout']['yaxis'] = {'title': 'GDP per Capita', 'type': 'log', 'gridcolor': '#FFFFFF'}
figure['layout']['hovermode'] = 'closest'
figure['layout']['plot_bgcolor'] = 'rgb(223, 232, 243)'
figure['layout']['sliders'] = {
'args': [
'slider.value', {
'duration': 400,
'ease': 'cubic-in-out'
}
],
'initialValue': '1952',
'plotlycommand': 'animate',
'values': years,
'visible': True
}
figure['layout']['updatemenus'] = [
{
'buttons': [
{
'args': [None, {'frame': {'duration': 500, 'redraw': False},
'fromcurrent': True, 'transition': {'duration': 300, 'easing': 'quadratic-in-out'}}],
'label': 'Play',
'method': 'animate'
},
{
'args': [[None], {'frame': {'duration': 0, 'redraw': False}, 'mode': 'immediate',
'transition': {'duration': 0}}],
'label': 'Pause',
'method': 'animate'
}
],
'direction': 'left',
'pad': {'r': 10, 't': 87},
'showactive': False,
'type': 'buttons',
'x': 0.1,
'xanchor': 'right',
'y': 0,
'yanchor': 'top'
}
]
sliders_dict = {
'active': 0,
'yanchor': 'top',
'xanchor': 'left',
'currentvalue': {
'font': {'size': 20},
'prefix': 'Year:',
'visible': True,
'xanchor': 'right'
},
'transition': {'duration': 300, 'easing': 'cubic-in-out'},
'pad': {'b': 10, 't': 50},
'len': 0.9,
'x': 0.1,
'y': 0,
'steps': []
}
custom_colors = {
'Asia': 'rgb(171, 99, 250)',
'Europe': 'rgb(230, 99, 250)',
'Africa': 'rgb(99, 110, 250)',
'Americas': 'rgb(25, 211, 243)',
#'Oceania': 'rgb(9, 255, 255)'
'Oceania': 'rgb(50, 170, 255)'
}
col_name_template = '{year}_{continent}_{header}_gapminder_grid'
year = 1952
for continent in continents:
data_dict = {
'xsrc': grid.get_column_reference(col_name_template.format(
year=year, continent=continent, header='lifeExp'
)),
'ysrc': grid.get_column_reference(col_name_template.format(
year=year, continent=continent, header='gdpPercap'
)),
'mode': 'markers',
'textsrc': grid.get_column_reference(col_name_template.format(
year=year, continent=continent, header='country'
)),
'marker': {
'sizemode': 'area',
'sizeref': 200000,
'sizesrc': grid.get_column_reference(col_name_template.format(
year=year, continent=continent, header='pop'
)),
'color': custom_colors[continent]
},
'name': continent
}
figure['data'].append(data_dict)
for year in years:
frame = {'data': [], 'name': str(year)}
for continent in continents:
data_dict = {
'xsrc': grid.get_column_reference(col_name_template.format(
year=year, continent=continent, header='lifeExp'
)),
'ysrc': grid.get_column_reference(col_name_template.format(
year=year, continent=continent, header='gdpPercap'
)),
'mode': 'markers',
'textsrc': grid.get_column_reference(col_name_template.format(
year=year, continent=continent, header='country'
)),
'marker': {
'sizemode': 'area',
'sizeref': 200000,
'sizesrc': grid.get_column_reference(col_name_template.format(
year=year, continent=continent, header='pop'
)),
'color': custom_colors[continent]
},
'name': continent
}
frame['data'].append(data_dict)
figure['frames'].append(frame)
slider_step = {'args': [
[year],
{'frame': {'duration': 300, 'redraw': False},
'mode': 'immediate',
'transition': {'duration': 300}}
],
'label': year,
'method': 'animate'}
sliders_dict['steps'].append(slider_step)
figure['layout']['sliders'] = [sliders_dict]
py.icreate_animations(figure, 'gapminder_example'+str(time.time()))
Note: Strange but the code executed successfully for me with the above mentioned typo as well!
Demo output.
You need plotly >= 2.0.0
try
pip install plotly --upgrade
As others have mentioned, the documentation is incorrect. But simply replacing all slider with sliders will still give an error. Therefore, here's a self contained example.
http://nbviewer.jupyter.org/gist/empet/365cf202391bf7a58021388fadd52004

Hyperlink will not show Display proper text

I am trying to add a hyperlink to a cell to open a folder the code below makes the hyperlink in the proper cell and is when clicked redirects to the proper folder but it does not display the text provided it instead displays the folder name e.g. (:C:\Documents and Settings\abulle\Desktop\Python-Stuff\Spec-Load\Formatted\) instead of 'Folder'
sheet.Hyperlinks.Add( Anchor = sheet.Cells(7,21), Address = "C:\\Python-Stuff\\Spec-Load\\Formatted\\" , TextToDisplay = "Folder")
I have a stopgap answer, a kludge. I don't have time at the moment to find a better answer. If this was part of my day job I'd spend the time to find out what's going on.
I've had the same issue (Excel shows the link address as the cell text instead of the TextToDisplay value supplied on Hyperlinks.Add())
My code works under unit test when invoked by running the Python 2.7 interpreter - the value of the 'TextToDisplay' argument is displayed in the cell. The 'production' code (built using py2exe) displays the hyperlink. I'll find out why some day (this is low background work.)
Hyperlinks.Add returns the Hyperlink object it just added. The workaround is to examine the TextToDisplay property of that object - if it's not what I want, I assign the correct value to it.
link = sheet.Hyperlinks.Add( Anchor = sheet.Cells(7,21),
Address = u"C:\\Python-Stuff\\Spec-Load\\Formatted\\" ,
TextToDisplay = u"Folder")
if link.TextToDisplay != u"Folder":
link.TextToDisplay = u"Folder" # kludge
try this
def addHyperlink(self, uri_1, summa_, sheetId, rowIndex, colIndex):
requests = []
requests.append({
"updateCells": {
"rows": [{
"values": [{
'userEnteredValue': {'numberValue': floatG(summa_)}, #
'effectiveValue': {'numberValue': floatG(summa_)},
'formattedValue': "р." + summa_,
'userEnteredFormat': {
'numberFormat': {'type': 'NUMBER', 'pattern': '[$р.-419]#,##0.00'},
'backgroundColor': {'red': 1, 'green': 1, 'blue': 0.6}, 'borders': {
'top': {
'style': 'SOLID', 'width': 1, 'color': {}, 'colorStyle': {'rgbColor': {}}},
'bottom': {
'style': 'SOLID', 'width': 1, 'color': {}, 'colorStyle': {'rgbColor': {}}},
'left': {
'style': 'SOLID', 'width': 1, 'color': {}, 'colorStyle': {'rgbColor': {}}},
'right': {
'style': 'SOLID', 'width': 1, 'color': {}, 'colorStyle': {'rgbColor': {}}}},
'horizontalAlignment': 'RIGHT', 'verticalAlignment': 'BOTTOM',
'textFormat': {
'foregroundColor': {'red': 0.06666667, 'green': 0.33333334, 'blue': 0.8},
'fontFamily': 'Arial', 'underline': True,
'foregroundColorStyle': {
'rgbColor': {'red': 0.06666667, 'green': 0.33333334, 'blue': 0.8}},
'link': {'uri': uri_1}
},
'hyperlinkDisplayType': 'LINKED',
'backgroundColorStyle': {'rgbColor': {'red': 1, 'green': 1, 'blue': 0.6}}
}
, 'hyperlink': uri_1, 'note': 'макс',
}
]
}], "fields": "userEnteredFormat(numberFormat,backgroundColor,horizontalAlignment,verticalAlignment,textFormat)", "start": {
"sheetId": sheetId, "rowIndex": rowIndex, "columnIndex": colIndex}}})
body = {
"requests": requests}
request = self.service.spreadsheets().batchUpdate(spreadsheetId=self.spreadsheetId, body=body)
return request.execute()

Categories