Unable to load DataTable with Dash 0.41 - python

Since the version 0.41.0 of dash, the following code is on error :
import dash
from dash_table_experiments import DataTable
app = dash.Dash() app.layout = DataTable( id='datatable', rows=[{'V'+dash.__version__: i} for i in range(5)] )
app.run_server(debug=True)
whereas version 0.40.0 displays the table properly.
Would any one know what has changed ?
Thanks for your help ;

From the README file on the dash-table-experiements github page:
dash-table-experiments
DEPRECATED
If you are looking for a first class data table component for Dash head on over to https://github.com/plotly/dash-table and check out the documentation https://dash.plot.ly/datatable.
The component is no longer supported. The dash-table component works really well, though. Here is a basic example:
import dash
import numpy as np
import pandas
from dash_table import DataTable
app = dash.Dash()
df = pandas.DataFrame(np.arange(30).reshape(5, 6))
app.layout = DataTable(id='datatable',
columns=[{"name": i, "id": i} for i in df.columns],
data=df.to_dict(orient='records'))
if __name__ == '__main__':
app.run_server(debug=True)

Related

Python Dash TypeError: cannot convert 'NoneType' object to bytes

I am trying to build a dashboard using Dash. I keep getting this error when I go to the default website http://127.0.0.1:8050/ and I get TypeError: cannot convert 'NoneType' object. Check the image for the error. My code does not have any mistakes and I was able to run it before and the dashboard would work perfectly. Can someone please help me? Here is the code:
import dash # (version 1.12.0) pip install dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import datetime
from datetime import date
app = dash.Dash(__name__)
# App layout
app.layout = html.Div([
html.H1("Snodas SWE/SD For January", style={'text-align': 'center'}),
dcc.DatePickerSingle(
id='my-date-picker-single',
min_date_allowed=date(2020, 1, 1),
max_date_allowed=date(2020, 12, 30),
initial_visible_month=date(2020, 1, 1),
date=date(2020, 1, 1)
),
html.Div(id='output-container-date-picker-single'),
dcc.Checklist(
options=[
{'label': 'SWE', 'value': 'SWE'},
{'label': 'SD', 'value': 'SD'}
],
labelStyle={'display': 'inline-block'}
),
html.Iframe(id='map', srcDoc=open('map1.html', 'r').read(), width='100%', height='1000')
])
#app.callback(
Output('map', 'srcDoc'),
Input('my-date-picker-single', 'date'))
def update_output(date):
return open('map_swe_sd_{}.html'.format(str(date)), 'r').read()
if __name__ == "__main__":
app.run_server(debug = True)
Error Message
Try this:
#app.callback(
Output('map', 'srcDoc'),
Input('my-date-picker-single', 'date'))
def update_output(date):
if not date:
raise dash.exceptions.PreventUpdate
return open('map_swe_sd_{}.html'.format(str(date)), 'r').read()
I am new to all of this, so I hope I do this right and according to the conventional rules:
I had the same problem when I simply tried to do the dash tutorial on the dash website.
There was something wrong with my installation of dash or with my python environment (I know that "something wrong is not really an identification of the problem). It seems like this is similar in your case since the tracebacks point to packages, right? After creating and activating a new python environment, and installing dash there, everything worked.
I hope this might help you as well.

Dash Sort editable table, but hide sort options from users

I have a dash table. Table allows edit. I want to sort the table by column, so that if user input data, the table is resorted right away. I achieve this like on the page https://dash.plotly.com/datatable/callbacks. The sort is already set when the page loads. I got stuck on the last step, where I want to hide the sort option from user. Is that possible?
Example on the image. I want to delete the arrows marked yellow, but keep sort by column 'pop'.
edited code example from https://dash.plotly.com/datatable/callbacks:
import dash
from dash.dependencies import Input, Output
import dash_table
import pandas as pd
app = dash.Dash(__name__)
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')
PAGE_SIZE = 5
app.layout = dash_table.DataTable(
id='table-multicol-sorting',
columns=[
{"name": i, "id": i} for i in sorted(df.columns)
],
data=df.to_dict('records'),
page_size=PAGE_SIZE,
sort_action='native',
sort_mode='multi',
sort_as_null=['', 'No'],
sort_by=[{'column_id': 'pop', 'direction': 'asc'}],
editable=True,
)
if __name__ == '__main__':
app.run_server(debug=True)
You can target the sort element and hide it using css like this:
span.column-header--sort {
display: none;
}
So you can put that code in a css file in your assets directory for example. See the documentation here for more information about ways to include styles in a dash app.
I am able to do it by sort_action='none' in Dash v1.16.2

Import of Dash module alters .csv files

I've run into a strange behaviour when using the Dash library and I apologies in advance as I don't think I can't make an example which is easy to reproduce, so instead I will include all the information I think is relevant.
I was trying to create a small dashboard which loaded some data and then plotted it in a bar chart. The code I used for this is below (it is adapted from the Docs):
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd
import os.path as path
def find_unique_id(data, first_name, second_name, season):
name = first_name + '_' + second_name
data_filt = data[data['season'] == season]
data_filt = data_filt[data_filt['name'] == name]
print(data_filt['unique_id'])
return data_filt['unique_id'].iloc[0]
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
path_data = path.join(path.dirname(path.dirname(path.abspath(__file__))), 'Processed', 'player_database.csv')
data = pd.read_csv(path_data)
unique_id = []
unique_id.append(find_unique_id(data, 'Harry', 'Kane', 2020))
unique_id.append(find_unique_id(data, 'Mohamed', 'Salah', 2020))
unique_id.append(find_unique_id(data, 'Heung-Min', 'Son', 2020))
fig = px.bar(data[data['unique_id'].isin(unique_id)], x="round", y="points_mean3", color="name", barmode="group")
app.layout = html.Div(children=[
html.H1(children='Hello Dash'),
html.Div(children='''
Dash: A web application framework for Python.
'''),
dcc.Graph(
id='example-graph',
figure=fig
)
])
if __name__ == '__main__':
app.run_server(debug=True)
The player_database.csv is loaded and detailed in the picture (notice the file sizes):
However now whenever I import any Dash related module even in a different file, it changes all the files in this folder, and appears to role them back to an earlier state. For example when I run the following code, you can see the change in file size happening:
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
This alters all the files in this directory (again as shown by the file size):
Does anyone know why this might be happening, has Dash got some kind of cache somewhere which loads the files it was working with from some previous state? I've tried googling and can't find anything on this.
Thanks

Map with Choroplethmapbox isn't showing in Dash

I am trying to build a map with Choroplethmapbox in Dash, but I cannot plot in that.
I test the geojson with another tool and in that tools, the map is drawn correctly, but not with Choroplethmapbox.
Any idea about what I am doing wrong?
Thanks
GeoJson:
https://gist.github.com/Tlaloc-Es/5c82834e5e4a9019a91123cb11f598c0
Python Dash Code:
import json
with open('mexico.geojson') as f:
counties = json.load(f)
fig = go.Figure(go.Choroplethmapbox(
geojson=counties,
locations=df['COV_'],
z=df['Enero'],
colorscale="Viridis", zmin=0, zmax=df['Enero'].max(),
marker_opacity=0.5, marker_line_width=0))
fig.update_layout(mapbox_style="carto-positron",
mapbox_zoom=3, mapbox_center = {"lat": 37.0902, "lon": -95.7129})
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
looks like you are missing the fig.show() at the bottom and import plotly.graph_objects as go at the top. The code below will open a map, but data is needed for the choropleth values. You have df in your code example but you did not include a csv. If you want to us the df that is in your code, import pandas, and create a data frame called df from the csv. Here is a link that can help with that. Pandas dataframes
import json
import plotly.graph_objects as go
with open(r'{insert file path here}.geojson') as f:
counties = json.load(f)
fig = go.Figure(go.Choroplethmapbox(
geojson=counties,
colorscale="Viridis", zmin=0, zmax=100,
marker_opacity=0.5, marker_line_width=0))
fig.update_layout(mapbox_style="carto-positron",
mapbox_zoom=3, mapbox_center = {"lat": 37.0902, "lon": -95.7129})
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()
Here is an example of using pandas with you json.Further explanation of the code below can be found here
from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
counties = json.load(response)
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
dtype={"fips": str})
import plotly.express as px
fig = px.choropleth(df, geojson=counties, locations='fips', color='unemp',
color_continuous_scale="Viridis",
range_color=(0, 12),
scope="usa",
labels={'unemp':'unemployment rate'}
)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()
I needed to add an id filed wit this code:
I used the code of this page: https://community.plot.ly/t/plot-a-shapefile-shp-in-a-choropleth-chart/27850
I had to solve a similar problem and this is my solution applied to your problem (although with px.choropleth_mapbox instead of graph_objects which I found confusing for choropleths).
The data that you link does not (at least not at the time of writing) have the column 'Enero'.
You never define a Dash-app (app.layout = ...), while you can probably serve without it and just have fig.show() as suggested, explicit beats implicit. Thus creating a layout section is better.
If I understand how it works, if you use GeoPandas you do not have to generate an 'id' or anything like that as you suggest in your own answer.
Anyways, hopefully my solution can serve as a working start for you. I added radio buttons so that you can select what data column to use for color.
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import plotly.express as px
import geopandas as gpd
print('Loading data...')
gdf = gpd.read_file('https://gist.githubusercontent.com/Tlaloc-Es/5c82834e5e4a9019a91123cb11f598c0/raw/709ce9126861ef7a7c7cc4afd6216a6750d4bbe1/mexico.geojson')
gdf = gdf.to_crs(epsg=4326)
print('Done!')
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
html.Div([
dcc.RadioItems(
id='radio-color_on',
options=[{'label': i, 'value': i} for i in ['AREA','PERIMETER']],
value='AREA',
labelStyle={'display': 'inline-block'}
),
],style={'width': '40%', 'display': 'inline-block',}),
html.Div([], style={'width':'100%'}),
html.Div([
dcc.Graph(id="fig")
],style={'width': '100%', 'display': 'inline-block', 'padding': '0 10',},),
])
#app.callback(
Output("fig", "figure"),
[Input("radio-color_on", "value")])
def draw_choropleth(color_on):
fig = px.choropleth_mapbox(gdf,
geojson=gdf.geometry,
locations=gdf.index,
color=color_on,
color_continuous_scale="Viridis",
#range_color=(0, 12),
mapbox_style="carto-positron",
zoom=4,
center = {"lat":gdf.centroid.y.mean(), "lon":gdf.centroid.x.mean()},
opacity=0.5,
)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0},
height=700,
)
return fig
if __name__ == '__main__':
app.run_server(debug=True)
Saving this code to a file "myapp.py" and running it in the terminal as python myapp.py starts the development served, firing up a web browser, navigating to the url that it uses (it writes it out in the terminal, usually 172.0.0.1:8050) gives you this:
I am running these versions, from the defaults anaconda channel.
dash 1.19.0
dash-core-components 1.3.1
dash-html-components 1.0.1
dash-renderer 1.1.2
flask 1.1.2
geopandas 0.8.1
PS. I actually used the data to ask a question about dash choropleth mapbox selection behavior (Selection behavior in plotly-dash Choropleth mapbox plot). Thanks!
I have similar problems. With the show method, it works fine, sometimes with the dash too (using only callbacks). The problem occurs due to the really old version of dash, installed via default channel of anaconda (only one version 1.4.1). After installation via conda-forge channel newer version (in my case 1.13.4) it works.
conda install -c conda-forge dash dash-core-components \
dash-html-components dash-renderer dash-table

Python Dash DataTable: row selection not working

When I set row_selectable as 'multi' in a DataTable, I would expect an extra column on the very left with checkboxes to select arbitrary rows. However, when I do it, that column does not contain any checkboxes. Therefore, row selection is not possible.
import dash
import dash_table
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv')
app = dash.Dash(__name__)
app.layout = dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in df.columns],
data=df.to_dict("rows"),
row_selectable='multi'
)
if __name__ == '__main__':
app.run_server(debug=True)
row_selectable='single' results in the same output. I am using Python 3.6.8, dash 0.39.0, dash-table 3.6.0
Can somebody help, please?
Please install the latest dash
pip install dash==1.12.0
This will fix the issue.

Categories