Labels inside Counties for a map

Hello,

Kind of a newbie question but I have not been able to find the proper answer. Instead of having the hover label, I was trying to find a way to show labels in each county Polygon. I have the following code:

init_notebook_mode()

data=pd.read_excel(‘AZ Sales by FIPS.xlsx’, dtype={‘FIPS’:object})

df_sample_r = data[data[‘State’] == ‘AZ’]

values = df_sample_r[‘Sales’].tolist()
fips = df_sample_r[‘FIPS’].tolist()

colorscale = [
‘rgb(193, 193, 193)’,
‘rgb(239,239,239)’,
‘rgb(195, 196, 222)’,
‘rgb(144,148,194)’,
‘rgb(101,104,168)’,
‘rgb(65, 53, 132)’
]

fig = ff.create_choropleth(
fips=fips, values=values, scope=[‘AZ’],
binning_endpoints=[1, 4, 7, 10, 13], colorscale=colorscale,
county_outline={‘color’: ‘rgb(0,0,0)’, ‘width’: 1.0}, round_legend_values=True,
legend_title=‘Sales by County’, title=‘AZ’
)
iplot(fig, filename=‘choropleth_arizona’)

Thank you,

Justin

Hi @JustinT,

There’s not a built-in way to do this at the moment, but a nice thing about figure figure factories is that they return a figure object that you can inspect and modify before displaying. Here’s one way to get there.

# Get hover trace
hover_scatter = [scatt for scatt in fig.data if scatt.mode == 'markers'][0]

# Update text to include only county (Not state, FIPS, ec.)
import re
def extract_county(text_val):
    return re.sub(r'County: (.*?)<br>.*', r'\1', text_val)

hover_scatter.text = [extract_county(text_val) for text_val in hover_scatter.text]

# Show text
hover_scatter.mode = 'markers+text'

# Set font properties
hover_scatter.textfont.size = 8

Basically what this is doing is

  1. Searching for the scatter trace that the hover tooltips are associated with
  2. Updating the marker text to include only the country (instead of the default text with State, FIPS, etc)
  3. Configuring the scatter trace to show the text at the marker location
  4. Setting the font size (you could also set the font family and color here if you want)

Hope that helps get you started!
-Jon

Hi Jon,

Thanks for the help much appreciated.

I am getting a slight error message when I attempt the first line of code.



Hi Jon,

Thanks for the help much appreciated.

I am getting a slight error message when I attempt the first line of code.

Get hover trace

​
hover_scatter = [scatt for scatt in fig.data() if scatt.mode == ‘markers’][0]
​
​---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
in ()
1 # Get hover trace
2
----> 3 hover_scatter = [scatt for scatt in fig.data() if scatt.mode == ‘markers’][0]
4

AttributeError: ‘dict’ object has no attribute ‘data’

I tried a few ways to get at the dictionary object but as a novice, I am still having difficulty. Any further help would be much appreciated and Thank you!

Justin

Hi @JustinT, my guess is that you’re using an older version of plotly.py. I’d recommend upgrading to version 3.2.1 if that’s an option for you.

Before version 3 is wasn’t possible to use property access syntax of graph objects. So you couldn’t write fig.data, instead you had to use fig.['data']. So in version 2 this first line would need to be

hover_scatter = [scatt for scatt in fig['data'] if scatt['mode'] == 'markers'][0]

And similarly, the other property access expressions would need to be converted to dict get item syntax.

Hope that helps!
-Jon

Hi @jmmease, looking at my version, it says I have version 3.2.1. I have had some issues using my sign in, which causes me to do everything in offline mode. Could that be the issue?

I am using Juptyer Notebook from Anaconda. If there is a better way, I am all ears.

I also tried some plotting from an article on medium that you were a part of. Really nice article! If I did not use the iplot command, I would get the following as a result:

Thank you for all the help in this matter and sorry for all the follow up questions. Just excited to use plotly and curious how to fix the issues.

Thanks again!
Justin

Hi @JustinT,

Let’s see. If you’re using version 3+ and you’re getting AttributeError: 'dict' object has no attribute 'data', then is sounds like the fig object you’re working with is a dictionary. You can build a figure object from a dict using the go.Figure constructor. So, as a full example…

# Build figure object (in case fig is a dictionary)
fig = go.Figure(fig)

# Get hover trace
hover_scatter = [scatt for scatt in fig.data if scatt.mode == 'markers'][0]

# Update text to include only county (Not state, FIPS, ec.)
import re
def extract_county(text_val):
    return re.sub(r'County: (.*?)<br>.*', r'\1', text_val)

hover_scatter.text = [extract_county(text_val) for text_val in hover_scatter.text]

# Show text
hover_scatter.mode = 'markers+text'

# Set font properties
hover_scatter.textfont.size = 8

For the FigureWidget case. Are you using the classic jupyter notebook or JupyterLab? In the classic notebook FigureWidget should just work if you have plotly.py 3+ installed along with recent versions of the notebook and ipywidgets packages.

If you’re working in JupyterLab, there are a few more moving parts. Follow the JupyterLab installation instruction at https://github.com/plotly/plotly.py#installation (either pip or conda is fine). Pay close attention to the versions number of everything to make sure everything is compatible.

If all of that doens’t help. Could you add the output of the following commands here.

  • pip list
  • conda list
  • jupyter nbextensions list (if classic notebook)
  • jupyter labextension list (if JupyterLab)

Hope that helps!
-Jon

1 Like

Hi @jmmease,

The code seemed to do the trick! Very appreciative of all the extra effort of looking into this for me. Your help was huge! 2 minor (I hope) follow up questions.

  1. How do I reposition the labels, if possible. I have a couple that are outside of the polygons just due to their small size (see picture below). I was looking at the X anchor but wasn’t 100% sure how to change it.
  2. After the labels are added, is it possible to change the hover back to show only the County and the Values? I wasn’t really sure how to add that column’s info back in.

For the FigureWidget:
I am working in the classic Jupyter Notebook. I updated Notebook and ipywidgets and received the same result.

Here is the output you suggested:
Package Version


alabaster 0.7.10
anaconda-client 1.6.14
anaconda-navigator 1.8.7
anaconda-project 0.8.2
appdirs 1.4.3
asn1crypto 0.24.0
astroid 1.6.3
astropy 3.0.2
attrs 18.1.0
Automat 0.7.0
Babel 2.5.3
backcall 0.1.0
backports.shutil-get-terminal-size 1.0.0
beautifulsoup4 4.6.0
bitarray 0.8.1
bkcharts 0.2
blaze 0.11.3
bleach 2.1.3
bokeh 0.13.0
boto 2.48.0
Bottleneck 1.2.1
certifi 2018.8.24
cffi 1.11.5
chardet 3.0.4
click 6.7
click-plugins 1.0.3
cligj 0.4.0
cloudpickle 0.5.3
clyent 1.2.2
colorama 0.3.9
comtypes 1.1.4
conda 4.5.11
conda-build 3.10.5
conda-verify 2.0.0
constantly 15.1.0
contextlib2 0.5.5
cryptography 2.2.2
cycler 0.10.0
Cython 0.28.2
cytoolz 0.9.0.1
dask 0.17.5
datashape 0.5.4
decorator 4.3.0
descartes 1.1.0
distributed 1.21.8
docutils 0.14
entrypoints 0.2.3
et-xmlfile 1.0.1
fastcache 1.0.2
filelock 3.0.4
Fiona 1.7.10
Flask 1.0.2
Flask-Cors 3.0.4
GDAL 2.2.2
geopandas 0.3.0
gevent 1.3.0
glob2 0.6
greenlet 0.4.13
h5py 2.8.0
heapdict 1.0.0
html5lib 1.0.1
hyperlink 18.0.0
idna 2.6
imageio 2.3.0
imagesize 1.0.0
incremental 17.5.0
ipykernel 4.8.2
ipython 6.4.0
ipython-genutils 0.2.0
ipywidgets 7.4.2
isort 4.3.4
itsdangerous 0.24
jdcal 1.4
jedi 0.12.0
Jinja2 2.10
jsonschema 2.6.0
jupyter 1.0.0
jupyter-client 5.2.3
jupyter-console 5.2.0
jupyter-core 4.4.0
jupyterlab 0.32.1
jupyterlab-launcher 0.10.5
keyring 13.2.1
kiwisolver 1.0.1
lazy-object-proxy 1.3.1
llvmlite 0.23.1
locket 0.2.0
lxml 4.2.1
MarkupSafe 1.0
matplotlib 2.2.2
mccabe 0.6.1
menuinst 1.4.14
mistune 0.8.3
mkl-fft 1.0.0
mkl-random 1.0.1
more-itertools 4.1.0
mpmath 1.0.0
msgpack-python 0.5.6
multipledispatch 0.5.0
munch 2.3.2
navigator-updater 0.2.1
nbconvert 5.3.1
nbformat 4.4.0
networkx 2.1
nltk 3.3
nose 1.3.7
notebook 5.6.0
numba 0.38.0
numexpr 2.6.5
numpy 1.14.3
numpydoc 0.8.0
odo 0.5.1
olefile 0.45.1
openpyxl 2.5.3
packaging 17.1
pandas 0.23.0
pandocfilters 1.4.2
parso 0.2.0
partd 0.3.8
path.py 11.0.1
pathlib2 2.3.2
patsy 0.5.0
pep8 1.7.1
pickleshare 0.7.4
Pillow 5.1.0
pip 10.0.1
pkginfo 1.4.2
plotly 3.2.1
pluggy 0.6.0
ply 3.11
prometheus-client 0.3.1
prompt-toolkit 1.0.15
psutil 5.4.5
psycopg2 2.7.5
py 1.5.3
pyasn1 0.4.4
pyasn1-modules 0.2.2
pycodestyle 2.4.0
pycosat 0.6.3
pycparser 2.18
pycrypto 2.6.1
pycurl 7.43.0.1
pyflakes 1.6.0
Pygments 2.2.0
pylint 1.8.4
pyodbc 4.0.24
pyOpenSSL 18.0.0
pyparsing 2.2.0
pyproj 1.9.5.1
PySAL 1.14.4.post1
pyshp 1.2.12
PySocks 1.6.8
pytest 3.5.1
pytest-arraydiff 0.2
pytest-astropy 0.3.0
pytest-doctestplus 0.1.3
pytest-openfiles 0.3.0
pytest-remotedata 0.2.1
python-dateutil 2.7.3
pytz 2018.4
PyWavelets 0.5.2
pywin32 223
pywinpty 0.5.1
PyYAML 3.12
pyzmq 17.0.0
QtAwesome 0.4.4
qtconsole 4.3.1
QtPy 1.4.1
requests 2.18.4
retrying 1.3.3
rope 0.10.7
Rtree 0.8.3
ruamel-yaml 0.15.35
scikit-image 0.13.1
scikit-learn 0.19.1
scipy 1.1.0
seaborn 0.8.1
Send2Trash 1.5.0
service-identity 17.0.0
setuptools 39.1.0
Shapely 1.6.4.post1
simplegeneric 0.8.1
singledispatch 3.4.0.3
six 1.11.0
snowballstemmer 1.2.1
sortedcollections 0.6.1
sortedcontainers 1.5.10
Sphinx 1.7.4
sphinxcontrib-websupport 1.0.1
spyder 3.3.1
spyder-kernels 0.2.6
SQLAlchemy 1.2.7
statsmodels 0.9.0
sympy 1.1.1
tables 3.4.4
tblib 1.3.2
terminado 0.8.1
testpath 0.3.1
toolz 0.9.0
tornado 5.0.2
traitlets 4.3.2
Twisted 18.7.0
typing 3.6.4
unicodecsv 0.14.1
urllib3 1.22
wcwidth 0.1.7
webencodings 0.5.1
Werkzeug 0.14.1
wheel 0.31.1
widgetsnbextension 3.4.2
win-inet-pton 1.0.1
win-unicode-console 0.5
wincertstore 0.2
wrapt 1.10.11
xlrd 1.1.0
XlsxWriter 1.0.4
xlwings 0.11.8
xlwt 1.3.0
zict 0.1.3
zope.interface 4.5.0
You are using pip version 10.0.1, however version 18.0 is available.
You should consider upgrading via the ‘python -m pip install --upgrade pip’ command.

Conda List:

packages in environment at C:\Users\jtanguay\AppData\Local\Continuum\anaconda3:

Name Version Build Channel

_ipyw_jlab_nb_ext_conf 0.1.0 py36he6757f0_0
alabaster 0.7.10 py36hcd07829_0
anaconda-client 1.6.14 py36_0
anaconda-navigator 1.8.7 py36_0
anaconda-project 0.8.2 py36hfad2e28_0
appdirs 1.4.3 py36h28b3542_0
asn1crypto 0.24.0 py36_0
astroid 1.6.3 py36_0
astropy 3.0.2 py36h452e1ab_1
attrs 18.1.0 py36_0
automat 0.7.0 py36_0
babel 2.5.3 py36_0
backcall 0.1.0 py36_0
backports 1.0 py36h81696a8_1
backports.shutil_get_terminal_size 1.0.0 py36h79ab834_2
beautifulsoup4 4.6.0 py36hd4cc5e8_1
bitarray 0.8.1 py36hfa6e2cd_1
bkcharts 0.2 py36h7e685f7_0
blas 1.0 mkl
blaze 0.11.3 py36h8a29ca5_0
bleach 2.1.3 py36_0
blosc 1.14.3 he51fdeb_0
bokeh 0.13.0 py36_0
boto 2.48.0 py36h1a776d2_1
bottleneck 1.2.1 py36hd119dfa_0
bzip2 1.0.6 hfa6e2cd_5
ca-certificates 2018.03.07 0
certifi 2018.8.24 py36_1
cffi 1.11.5 py36h945400d_0
chardet 3.0.4 py36h420ce6e_1
click 6.7 py36hec8c647_0
click-plugins 1.0.3 py36_1
cligj 0.4.0 py36_1
cloudpickle 0.5.3 py36_0
clyent 1.2.2 py36hb10d595_1
colorama 0.3.9 py36h029ae33_0
comtypes 1.1.4 py36_0
conda 4.5.11 py36_0
conda-build 3.10.5 py36_0
conda-env 2.6.0 h36134e3_1
conda-verify 2.0.0 py36h065de53_0
console_shortcut 0.1.1 h6bb2dd7_3
constantly 15.1.0 py36h28b3542_0
contextlib2 0.5.5 py36he5d52c0_0
cryptography 2.2.2 py36hfa6e2cd_0
curl 7.60.0 h7602738_0
cycler 0.10.0 py36h009560c_0
cython 0.28.2 py36hfa6e2cd_0
cytoolz 0.9.0.1 py36hfa6e2cd_0
dask 0.17.5 py36_0
dask-core 0.17.5 py36_0
datashape 0.5.4 py36h5770b85_0
decorator 4.3.0 py36_0
descartes 1.1.0 py36_0
distributed 1.21.8 py36_0
docutils 0.14 py36h6012d8f_0
entrypoints 0.2.3 py36hfd66bb0_2
et_xmlfile 1.0.1 py36h3d2d736_0
expat 2.2.5 he025d50_0
fastcache 1.0.2 py36hfa6e2cd_2
filelock 3.0.4 py36_0
fiona 1.7.10 py36h5bf8d1d_0
flask 1.0.2 py36_1
flask-cors 3.0.4 py36_0
freetype 2.8 h51f8f2c_1
freexl 1.0.5 hfa6e2cd_0
gdal 2.2.2 py36hcebd033_1
geopandas 0.3.0 py36_0
geos 3.6.2 h9ef7328_2
get_terminal_size 1.0.0 h38e98db_0
gevent 1.3.0 py36hfa6e2cd_0
glob2 0.6 py36hdf76b57_0
greenlet 0.4.13 py36hfa6e2cd_0
h5py 2.8.0 py36hf7173ca_0
hdf4 4.2.13 h712560f_2
hdf5 1.8.18 hcf527f2_1
heapdict 1.0.0 py36_2
html5lib 1.0.1 py36h047fa9f_0
hyperlink 18.0.0 py36_0
icc_rt 2017.0.4 h97af966_0
icu 58.2 ha66f8fd_1
idna 2.6 py36h148d497_1
imageio 2.3.0 py36_0
imagesize 1.0.0 py36_0
incremental 17.5.0 py36_0
intel-openmp 2018.0.0 8
ipykernel 4.8.2 py36_0
ipython 6.4.0 py36_0
ipython_genutils 0.2.0 py36h3c5d0ee_0
ipywidgets 7.4.2 py36_0
isort 4.3.4 py36_0
itsdangerous 0.24 py36hb6c5a24_1
jdcal 1.4 py36_0
jedi 0.12.0 py36_1
jinja2 2.10 py36h292fed1_0
jpeg 9b hb83a4c4_2
jsonschema 2.6.0 py36h7636477_0
jupyter 1.0.0 py36_7
jupyter_client 5.2.3 py36_0
jupyter_console 5.2.0 py36h6d89b47_1
jupyter_core 4.4.0 py36h56e9d50_0
jupyterlab 0.32.1 py36_0
jupyterlab_launcher 0.10.5 py36_0
kealib 1.4.7 h1834499_5
keyring 13.2.1 py36_0
kiwisolver 1.0.1 py36h12c3424_0
krb5 1.16.1 h038dc86_6
lazy-object-proxy 1.3.1 py36hd1c21d2_0
libboost 1.67.0 hd9e427e_4
libcurl 7.60.0 hc4dcbb0_0
libgdal 2.2.2 h309aa3f_1
libiconv 1.15 h1df5818_7
libkml 1.3.0 he5f2a48_4
libnetcdf 4.4.1.1 hf30bd8e_8
libpng 1.6.34 h79bbb47_0
libpq 10.5 h5fe2233_0
libsodium 1.0.16 h9d3ae62_0
libspatialindex 1.8.5 h6538335_2
libspatialite 4.3.0a h383548d_18
libssh2 1.8.0 hd619d38_4
libtiff 4.0.9 hb8ad9f9_1
libxml2 2.9.8 hadb2253_1
libxslt 1.1.32 hf6f1972_0
llvmlite 0.23.1 py36hcacf6c6_0
locket 0.2.0 py36hfed976d_1
lxml 4.2.1 py36heafd4d3_0
lzo 2.10 h6df0209_2
m2w64-gcc-libgfortran 5.3.0 6
m2w64-gcc-libs 5.3.0 7
m2w64-gcc-libs-core 5.3.0 7
m2w64-gmp 6.1.0 2
m2w64-libwinpthread-git 5.0.0.4634.697f757 2
markupsafe 1.0 py36h0e26971_1
matplotlib 2.2.2 py36h153e9ff_1
mccabe 0.6.1 py36hb41005a_1
menuinst 1.4.14 py36hfa6e2cd_0
mistune 0.8.3 py36hfa6e2cd_1
mkl 2018.0.2 1
mkl-service 1.1.2 py36h57e144c_4
mkl_fft 1.0.1 py36h452e1ab_0
mkl_random 1.0.1 py36h9258bd6_0
more-itertools 4.1.0 py36_0
mpmath 1.0.0 py36hacc8adf_2
msgpack-python 0.5.6 py36he980bc4_0
msys2-conda-epoch 20160418 1
multipledispatch 0.5.0 py36_0
munch 2.3.2 py36_0
navigator-updater 0.2.1 py36_0
nbconvert 5.3.1 py36h8dc0fde_0
nbformat 4.4.0 py36h3a5bc1b_0
networkx 2.1 py36_0
nltk 3.3.0 py36_0
nose 1.3.7 py36h1c3779e_2
notebook 5.6.0 py36_0
numba 0.38.0 py36h830ac7b_0
numexpr 2.6.5 py36hcd2f87e_0
numpy 1.14.3 py36h9fa60d3_1
numpy-base 1.14.3 py36h555522e_1
numpydoc 0.8.0 py36_0
odo 0.5.1 py36h7560279_0
olefile 0.45.1 py36_0
openjpeg 2.3.0 h5ec785f_1
openpyxl 2.5.3 py36_0
openssl 1.0.2p hfa6e2cd_0
packaging 17.1 py36_0
pandas 0.23.0 py36h830ac7b_0
pandoc 1.19.2.1 hb2460c7_1
pandocfilters 1.4.2 py36h3ef6317_1
parso 0.2.0 py36_0
partd 0.3.8 py36hc8e763b_0
path.py 11.0.1 py36_0
pathlib2 2.3.2 py36_0
patsy 0.5.0 py36_0
pep8 1.7.1 py36_0
pickleshare 0.7.4 py36h9de030f_0
pillow 5.1.0 py36h0738816_0
pip 10.0.1 py36_0
pkginfo 1.4.2 py36_1
plotly 3.2.1 py36h28b3542_0
pluggy 0.6.0 py36hc7daf1e_0
ply 3.11 py36_0
proj4 4.9.3 hcf24537_7
prometheus_client 0.3.1 py36h28b3542_0
prompt_toolkit 1.0.15 py36h60b8f86_0
psutil 5.4.5 py36hfa6e2cd_0
psycopg2 2.7.5 py36h74b6da3_0
py 1.5.3 py36_0
pyasn1 0.4.4 py36h28b3542_0
pyasn1-modules 0.2.2 py36_0
pycodestyle 2.4.0 py36_0
pycosat 0.6.3 py36h413d8a4_0
pycparser 2.18 py36hd053e01_1
pycrypto 2.6.1 py36hfa6e2cd_8
pycurl 7.43.0.1 py36h74b6da3_0
pyflakes 1.6.0 py36h0b975d6_0
pygments 2.2.0 py36hb010967_0
pylint 1.8.4 py36_0
pyodbc 4.0.24 py36h6538335_0
pyopenssl 18.0.0 py36_0
pyparsing 2.2.0 py36h785a196_1
pyproj 1.9.5.1 py36_0
pyqt 5.9.2 py36h1aa27d4_0
pysal 1.14.4.post1 py36_1
pyshp 1.2.12 py36_0
pysocks 1.6.8 py36_0
pytables 3.4.4 py36h0f9c03a_0
pytest 3.5.1 py36_0
pytest-arraydiff 0.2 py36_0
pytest-astropy 0.3.0 py36_0
pytest-doctestplus 0.1.3 py36_0
pytest-openfiles 0.3.0 py36_0
pytest-remotedata 0.2.1 py36_0
python 3.6.5 h0c2934d_0
python-dateutil 2.7.3 py36_0
pytz 2018.4 py36_0
pywavelets 0.5.2 py36hc649158_0
pywin32 223 py36hfa6e2cd_1
pywinpty 0.5.1 py36_0
pyyaml 3.12 py36h1d1928f_1
pyzmq 17.0.0 py36hfa6e2cd_1
qt 5.9.5 vc14he4a7d60_0 [vc14]
qtawesome 0.4.4 py36h5aa48f6_0
qtconsole 4.3.1 py36h99a29a9_0
qtpy 1.4.1 py36_0
requests 2.18.4 py36h4371aae_1
retrying 1.3.3 py36_2
rope 0.10.7 py36had63a69_0
rtree 0.8.3 py36_0
ruamel_yaml 0.15.35 py36hfa6e2cd_1
scikit-image 0.13.1 py36hfa6e2cd_1
scikit-learn 0.19.1 py36h53aea1b_0
scipy 1.1.0 py36h672f292_0
seaborn 0.8.1 py36h9b69545_0
send2trash 1.5.0 py36_0
service_identity 17.0.0 py36h28b3542_0
setuptools 39.1.0 py36_0
shapely 1.6.4 py36hc90234e_0
simplegeneric 0.8.1 py36_2
singledispatch 3.4.0.3 py36h17d0c80_0
sip 4.19.8 py36h6538335_0
six 1.11.0 py36h4db2310_1
snappy 1.1.7 h777316e_3
snowballstemmer 1.2.1 py36h763602f_0
sortedcollections 0.6.1 py36_0
sortedcontainers 1.5.10 py36_0
sphinx 1.7.4 py36_0
sphinxcontrib 1.0 py36hbbac3d2_1
sphinxcontrib-websupport 1.0.1 py36hb5e5916_1
spyder 3.3.1 py36_1
spyder-kernels 0.2.6 py36_0
sqlalchemy 1.2.7 py36ha85dd04_0
sqlite 3.23.1 h35aae40_0
statsmodels 0.9.0 py36h452e1ab_0
sympy 1.1.1 py36h96708e0_0
tblib 1.3.2 py36h30f5020_0
terminado 0.8.1 py36_1
testpath 0.3.1 py36h2698cfe_0
tk 8.6.7 hcb92d03_3
toolz 0.9.0 py36_0
tornado 5.0.2 py36_0
traitlets 4.3.2 py36h096827d_0
twisted 18.7.0 py36hfa6e2cd_1
typing 3.6.4 py36_0
unicodecsv 0.14.1 py36h6450c06_0
urllib3 1.22 py36h276f60a_0
vc 14 h0510ff6_3
vs2015_runtime 14.0.25123 3
wcwidth 0.1.7 py36h3d5aa90_0
webencodings 0.5.1 py36h67c50ae_1
werkzeug 0.14.1 py36_0
wheel 0.31.1 py36_0
widgetsnbextension 3.4.2 py36_0
win_inet_pton 1.0.1 py36he67d7fd_1
win_unicode_console 0.5 py36hcdbd4b5_0
wincertstore 0.2 py36h7fe50ca_0
winpty 0.4.3 4
wrapt 1.10.11 py36he5f5981_0
xerces-c 3.2.1 h27bfe9a_0
xlrd 1.1.0 py36h1cb58dc_1
xlsxwriter 1.0.4 py36_0
xlwings 0.11.8 py36_0
xlwt 1.3.0 py36h1a4751e_0
xz 5.2.4 h2fa13f4_4
yaml 0.1.7 hc54c509_2
zeromq 4.2.5 hc6251cf_0
zict 0.1.3 py36h2d8e73e_0
zlib 1.2.11 h8395fce_2
zope 1.0 py36_1
zope.interface 4.5.0 py36hfa6e2cd_0

jupyter nbextensions list:
(base) C:>jupyter nbextensions list
Error executing Jupyter command ‘nbextensions’: [Errno ‘jupyter-nbextensions’ not found] 2

Was curious if this was the problem. I went to download via conda install -c conda-forge jupyter_contrib_nbextensions but was curious if that was the best method, since it stated it was downgrading several packages.

Sorry for the long winded message, but thank you for the help Jon!
Justin

Hi @JustinT,

If you’d like to show different text in the map than in the hover label then instead of directly modifying the trace produced by create_choropleth you should make a copy of it, change the properties of the copy, then add the copy to the figure.

Something like:

# Get hover trace
hover_scatter = [scatt for scatt in fig.data if scatt.mode == 'markers'][0]

# Copy hover trace to make text trace
text_scatter = go.Scatter(hover_scatter)

# Update text to include only county (Not state, FIPS, ec.)
import re
def extract_county(text_val):
    return re.sub(r'County: (.*?)<br>.*', r'\1', text_val)

text_scatter.text = [extract_county(text_val) for text_val in text_scatter.text]

# Show text
text_scatter.mode = 'markers+text'

# Set font properties
text_scatter.textfont.size = 8

Then to tweak the position of the text labels, convert the x/y coords to lists, modify the lists, then assign back to the trace.

xs = list(text_scatter.x)
ys = list(text_scatter.y)

# Move the 4th label down and to the right a little
xs[3] = xs[3] + 5
ys[3] = ys[3] - 3

# Update text trace
text_scatter.x = xs
text_scatter.y = ys

Then add the copied trace to the figure

fig.add_trace(text_scatter) 

Oh, I made a mistake in the one command. It should be jupyter nbextension list (No s in nbextension). Could you post this output? Here’s what the plotlywidget and jupyter-js-widgets parts should look like.

Known nbextensions:
  config dir: /anaconda3/envs/jupyter_editor_dev/etc/jupyter/nbconfig
    notebook section
      plotlywidget/extension  enabled 
      - Validating: OK
      jupyter-js-widgets/extension  enabled 
      - Validating: OK

Also, it looks like you have the the notebook, ipywidgets, and plotly packages installed through both pip and conda. I’d recommend uninstalling all three packages using both pip and conda, and then reinstalling them using one or the other.

If that doesn’t take care of it. Try creating a fresh conda environment (https://conda.io/docs/user-guide/tasks/manage-environments.html) and following the plotly installation instructions again in the new environment and see if things work there.

Hope that helps!
-Jon

I am also attempting to follow your code above. The below produces a county map but I am unable to get your code to work to add the county labels (in Spyder). I receive the same message ‘Figure’ object has no attribute ‘df_sample_r’. I am working in Plotly offline mode. Do I run your code after I create the map? I’m not sure at which step to add your code or what object to apply it to. Thank you for your help.

Preformatted textcore_states = [‘NE’, ‘IA’]
df_sample_r = ctyname_cum[ctyname_cum[‘STD_STATE’].isin(core_states)]

values = df_sample_r[‘Customer_Opp’].tolist()
fips = df_sample_r[‘FIPS5’].tolist()

colorscale = [
‘RGB(0,255,255)’, ‘RGB(131,139,139)’, ‘RGB(255,97,3)’]

fig = ff.create_choropleth(
fips=fips, values=values, scope=core_states, show_state_data=True,
colorscale=colorscale, round_legend_values=True,
plot_bgcolor=‘rgb(229,229,229)’,
paper_bgcolor=‘rgb(229,229,229)’,
legend_title=‘HH by County’,
county_outline={‘color’: ‘rgb(255,255,255)’, ‘width’: 0.5},
exponent_format=True,
)
plot(fig, auto_open = True)

Hi @adamsj7,

The error message “‘Figure’ object has no attribute ‘df_sample_r’” implies that somewhere in the code you’re running there is a statement like fig.df_sample_r. If you’d like more help working through it, please post a full reproducible example (including imports and sample data) and place the example inside a fenced code block (See https://help.github.com/en/articles/creating-and-highlighting-code-blocks).

-Jon

@jmmease
Thank you for your quick reply. I have fenced the code below with explanations of key column headers. I am unable to provide the data due to data sharing rules. I hope the code with explanation will suffice. The below code works to create the map but the goal is to label the counties as well.

#ctyname_cum is a data frame with columns
#county FIPS codes = FIPS5
#categorical variable to color counties by = 'Customer_Opp'
#county names = 'Name'

core_states = [‘NE’, ‘IA’]
df_sample_r = ctyname_cum[ctyname_cum[‘STD_STATE’].isin(core_states)]

values = df_sample_r[‘Customer_Opp’].tolist()
fips = df_sample_r[‘FIPS5’].tolist()

colorscale = [
‘RGB(0,255,255)’, ‘RGB(131,139,139)’, ‘RGB(255,97,3)’]

fig = ff.create_choropleth(
fips=fips, values=values, scope=core_states, show_state_data=True,
colorscale=colorscale, round_legend_values=True,
plot_bgcolor=‘rgb(229,229,229)’,
paper_bgcolor=‘rgb(229,229,229)’,
legend_title=‘HH by County’,
county_outline={‘color’: ‘rgb(255,255,255)’, ‘width’: 0.5},
exponent_format=True,
)
plot(fig, auto_open = True)

Hi @adamsj7,

I don’t see anything in your code that looks like it should result in that error. Could you also add a full stack trace of the error you’re seeing?

It would also be helpful if you could make up some simple sample data for the data frame that results in the error.

-Jon

Hi, I am having a similar issue where I want to display county labels on my map as the hover doesn’t seem to work (I think this is a known issue as I saw other people struggle with this too).

I tried to use the solution provided here but it did not end up changing my plot…Can someone please help me understand what I am doing wrong? I see that it’s supposed to extract county names with some regex rules from fig.data, and I see that those are there in data.fig but I’m not sure really how to put those values on the map.

My code looks like this:

values = dfCounty['PercentChangeSIR'].tolist()
fips = dfCounty['FIPS'].tolist()

#diverging colorscheme
colorscale=["#006837","#1a9850","#66bd63","#a6d96a","#d9ef8b","#ffffbf",
"#fee08b","#fdae61","#f46d43","#d73027","#a50026","#8e0152"]

#colorscheme that is colorblind friendly
colorscale_colorblind=[ "#276419","#4d9221","#7fbc41","#b8e186","#e6f5d0","#f7f7f7",
             "#fde0ef","#f1b6da","#de77ae","#c51b7d","#8e0152","#8e0152"]


fig = ff.create_choropleth(
    fips=fips, values=values, scope=['CA'],
    binning_endpoints=[-100, -80, -60, -40, -20, 0, 20, 40, 60, 80, 100], colorscale=colorscale,
    county_outline={'color': 'rgb(255,255,255)', 'width': 0.5}, round_legend_values=True, show_state_data=True, show_hover=True,
    legend_title='% Change, 2015 to 2017', title='C. difficile Infection by County in California'
)


fig.write_image("images/fig1.png", scale=4)
fig.layout.template = None
fig.show()