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
Related
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!
I downloaded some recent earthquake data for visualizing, and I am getting error:
ValueError:
Invalid element(s) received for the 'size' property of scattergeo.marker
Invalid elements include: [-0.55, -0.44999999999999996, -0.15, -0.5, -1.5, -0.6, -0.75, -1.9500000000000002, -1.85, -1.5]
The 'size' property is a number and may be specified as:
- An int or float in the interval [0, inf]
- A tuple, list, or one-dimensional numpy array of the above
How do I remove the negative elements from the JSON file that I'm using?
here is my code:
import json
from plotly.graph_objs import Layout
from plotly import offline
# Explore the structure of the data.
filename = "data/7_day_eq.json"
with open(filename, encoding="utf8") as f:
all_eq_data = json.load(f)
# Create a file that is more readable.
readable_file = "data/readable_7_day_eq_data.json"
with open(readable_file, 'w') as f:
json.dump(all_eq_data, f, indent=4)
# Take all the information from features key.
all_eq_dicts = all_eq_data['features']
# Get all the magnitudes.
mags, lons, lats, hover_texts = [], [], [], []
for eq_dicts in all_eq_dicts:
mags.append(eq_dicts['properties']['mag'])
lons.append(eq_dicts['geometry']['coordinates'][0])
lats.append(eq_dicts['geometry']['coordinates'][1])
hover_texts.append(eq_dicts['properties']['title'])
# Map the earthquakes.
data = [{
'type': 'scattergeo',
'lon': lons,
'lat': lats,
'text': hover_texts,
'marker': {
'size': [5*mag for mag in mags],
'color': mags,
'colorscale': 'Viridis',
'reversescale': True,
'colorbar': {'title': 'Magnitude'},
},
}]
layout_title = all_eq_data['metadata']['title']
my_layout = Layout(title=f'Global Earthquakes{layout_title}')
fig = {'data': data, 'layout': my_layout}
offline.plot(fig, filename='global_earthquakes_7_days.html')
The data for my "7_day_eq.json" came from https://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson.php Past 7 days section and copied all earthquakes into a file.
The easiest would be to use the absolute value, to make all of the values positive
# Map the earthquakes.
data = [{
'type': 'scattergeo',
'lon': lons,
'lat': lats,
'text': hover_texts,
'marker': {
'size': [abs(5*mag) for mag in mags],
'color': mags,
'colorscale': 'Viridis',
'reversescale': True,
'colorbar': {'title': 'Magnitude'},
},
}]
or if you don't want to make them positive, but just 0 a simple if will do that
# Map the earthquakes.
data = [{
'type': 'scattergeo',
'lon': lons,
'lat': lats,
'text': hover_texts,
'marker': {
'size': [5*mag if mag > 0 else 0.1 for mag in mags],
'color': mags,
'colorscale': 'Viridis',
'reversescale': True,
'colorbar': {'title': 'Magnitude'},
},
}]
I used 0.1 there as the error message
The 'size' property is a number and may be specified as:
- An int or float in the interval [0, inf]
- A tuple, list, or one-dimensional numpy array of the above
suggests, that the interval is open, meaning you can't use 0
Just make 2 separate mags lists depending of whether you want it as positives or 0 replaced as below and it should work
mags_zero_replaced = [mag if mag > 0 else 0 for mag in mags]
mags_postive_converted = [abs(mag) for mag in mags]
data = [{
'type': 'scattergeo',
'lon': lons,
'lat': lats,
'text': hover_texts,
'marker': {
'size': [5*mag for mag in mags_zero_replaced],
'color': mags,
'colorscale': 'Viridis',
'reversescale': True,
'colorbar': {'title': 'Magnitude'},
},
}]
import plotly
import plotly.graph_objs as go
import matplotlib.pyplot as plt
import numpy as np
plotly.offline.init_notebook_mode(connected=True)
colorscale='Earth'
#print(" : Min : Q1 : Median : Q3 : Max : Mean : Good Mean : Good STD : Outliers :")
data = [
{
'x': ['Min','Min','Min','Min','Min'],
'y': ['config1','config2','config3','config4','config5'],
'mode': 'markers',
'marker': {
'color': [0.89,0.892,0.886,0.901,0.869],
'size': [30, 30, 30, 30, 30],
'showscale': False,
'colorscale':colorscale,
'reversescale':True,
'cmin':0.865,
'cmax':0.901,
}
},
{
'x': ['Q1','Q1','Q1','Q1','Q1'],
'y': ['config1','config2','config3','config4','config5'],
'mode': 'markers',
'marker': {
'color': [0.912,0.908,0.892,0.915,0.889],
'size': [30, 30, 30, 30, 30],
'showscale': False,
'colorscale':colorscale,
'reversescale':True,
'cmin':0.885,
'cmax':0.915,
}
},
{
'x': ['Median','Median','Median','Median','Median'],
'y': ['config1','config2','config3','config4','config5'],
'mode': 'markers',
'marker': {
'color': [0.919,0.912,0.914,0.917,0.9],
'size': [30, 30, 30, 30, 30],
'showscale': False,
'colorscale':colorscale,
'reversescale':True,
'cmin':0.89,
'cmax':0.919,
}
},
{
'x': ['Q3','Q3','Q3','Q3','Q3'],
'y': ['config1','config2','config3','config4','config5'],
'mode': 'markers',
'marker': {
'color': [0.929,0.919,0.925,0.922,0.909],
'size': [30, 30, 30, 30, 30],
'showscale': False,
'colorscale':colorscale,
'reversescale':True,
'cmin':0.90,
'cmax':0.929,
}
},
{
'x': ['Max','Max','Max','Max','Max'],
'y': ['config1','config2','config3','config4','config5'],
'mode': 'markers',
'marker': {
'color': [0.95,0.932,0.933,0.935,0.935],
'size': [30, 30, 30, 30, 30],
'showscale': False,
'colorscale':colorscale,
'reversescale':True,
'cmin':0.93,
'cmax':0.95,
}
},
{
'x': ['Mean','Mean','Mean','Mean','Mean'],
'y': ['config1','config2','config3','config4','config5'],
'mode': 'markers',
'marker': {
'color': [0.921,0.912,0.91,0.918,0.9],
'size': [30, 30, 30, 30, 30],
'showscale': False,
'colorscale':colorscale,
'reversescale':True,
'cmin':0.898,
'cmax':0.921,
}
}
]
layout = go.Layout(title='Parameters of evaluation', xaxis=dict(range=[-0.5, 10]), yaxis=dict(range=[-0.5, 5.5]))
fig = go.Figure(data=data, layout=layout)
#plotly.offline.iplot(data, filename='scatter-colorscale')
plotly.offline.iplot(fig)
Hello all i am working on a visualization, just started with plotly today, it is so cool. Anyways, I wish to add colormap at the side of the diagram, for what ever color scheme I chose, for me it is probably impossible to find a global colormap because my color gradient start and end points are different. But how can I at least add a colormap at the side which show which is highest color and what is the lowest color. Is there a easy way?
I want to add colormap like this, at right hand side
{
'x': ['Mean','Mean','Mean','Mean','Mean'],
'y': ['config1','config2','config3','config4','config5'],
'mode': 'markers,text',
'marker': {
'colorbar':dict(nticks=3,tickmode='array',tickvals=[2,4.5,7],showticklabels=True,ticktext=['lowest','middle','highest']),
'size': [30, 30, 30, 30, 30],
'showscale': True,
'colorscale':colorscale,
'reversescale':True,
'opacity':0
}
}
I added one of the hack like this, to solve my problem for now. Others can suggest me better way to do it. I added a extra trace with opacity zero and added a custom colorbar to it. It enabled me to add a colorbar which does not mess with other data. I could have added this colorbar in any of the trace too.
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 :)
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()