Git Product home page Git Product logo

branca's Introduction

branca's People

Contributors

achieveordie avatar ajabep avatar balthasarschachtner avatar bastiengauthier avatar bibmartin avatar bwest2397 avatar conengmo avatar deelaka avatar desrod avatar dstein64 avatar fitoprincipe avatar florinandrei avatar gillesc avatar haudinflorence avatar knil-sama avatar kota7 avatar martinfleis avatar matsavage avatar nanodan avatar ndswaef avatar ocefpaf avatar pre-commit-ci[bot] avatar psarka avatar samchorlton avatar simoubuntu avatar thomasbur avatar tomboehling avatar wd60622 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

branca's Issues

Feature request: colormap with background

Code Sample

import folium
import pandas as pd
import folium.plugins

import branca
import branca.colormap as cm

data = [
    [33.823400, -118.12194, 99.23],
    [33.823500, -118.12294, 95.23],
    [33.823600, -118.12394, 91.23],
    [33.823700, -118.12494, 90.00]
]

df = pd.DataFrame(data, columns=['latitude','longitude','data'])

x_start = (df['latitude'].max() + df['latitude'].min()) / 2
y_start = (df['longitude'].max() + df['longitude'].min()) / 2
start_coord = (x_start, y_start)


colormap = cm.LinearColormap(colors=['red','lightblue'],
                             index=[df['data'].min(),df['data'].max()],
                             vmin=df['data'].min(),vmax=df['data'].max())

colormap.caption = 'Data [units]'

map = folium.Map(location=start_coord, zoom_start=12)


lat = list(df.latitude)
lon = list(df.longitude)
dat = list(df.data)


for loc, p in zip(zip(lat, lon), dat):
    folium.Circle(
        location=loc,
        radius=10,
        fill=True,
        color=colormap(p),
        fill_opacity=0.7
    ).add_to(map)

map.add_child(colormap)
map.save('index.html')

Problem description

Code above creates colored points, and displays a colormap to show what data value each color corresponds to. This is great but it would be even better if a background colour could be selected. This slightly hacky work-around does exactly what I want:
https://stackoverflow.com/a/50427006/4988601

I'd be happy to try and plumb this into folium itself if a few people show some interest in this feature (I'm fairly new to folium so any pointers on what methods/classes I'd need to poke around in would be appreciated).

Expected Output

Colormap with an optional background color rectangle to help it stand out.

Output of folium.__version__

0.10.0

Colormap banding

When attaching a LinearColormap to a folium.raster_layers.TileLayer map, I'm getting banding in the fill

image
This appears to persist across various OS and browser combinations

I'm creating the colour map as

import branca.colormap as cm
import seaborn as sns

#[...]

cmap = sns.color_palette("YlGnBu", 12)
colormap = cm.LinearColormap(colors=cmap, vmin=vmin, vmax=vmax)
m.add_child(colormap)

#[...]

I've isolated the problem with the rect width being set here
https://github.com/python-visualization/branca/blob/master/branca/templates/color_scale.js#L48

For my case, this function is returning a width of ~0.8 (although each rect is slightly different widths).

If I set width=1.5 the problem is resolved
image

I'm wondering if this is intended behaviour, if it's a bug, and/or if there are any unintended consequences to changing the width.

Release

@BibMartin once you think it is ready let's create the release and a PyPI entry. I can to the latter for you.

Feature request: branca colormap accepted as a parameter ImageOverlay

Code Sample

import folium
import folium.plugins
import numpy as np

import branca
import branca.colormap as cm

data = np.random.rand(538,892)*100

colormap = cm.LinearColormap(colors=['red','lightblue'],
                             index=[50],
                             vmin=0,vmax=100)

map = folium.Map(location=[50.5039, 4.4699], zoom_start=12)
folium.raster_layers.ImageOverlay(
    image=data,
    bounds=[[53.804418158693835, -0.9254649843200244], [47.42086714394442, 9.65841513678867]],
    opacity=0.7,
    crs='EPSG4326',
    colormap=colormap         
).add_to(map)

map.add_child(colormap)

Problem description
Code above creates a raster map over Central Europe. Unfortunately the only possibility to make it colored it is through a matplotlib.colors that however doesn't allow to define vmin vmax.

Expected output
By using the branca.colormap LinearColormap and StepColormaap as a parameter in ImageOverlay this issue should be solved and one should be able to define both colormap and color range for any raster.

Output of folium.version
folium 0.14.0

Issue with LinearColormap to_step method?

Hi, I was trying to generate a step colour scale from a linear scale providing index but it seems that it generates one less colour:

test_data = [10, 12, 17, 25, 27, 29, 31, 54, 58, 59, 61, 69, 71, 72, 86, 87, 90, 91]

color = cm.LinearColormap(['red', 'green']).to_step(index=test_data)

for i, x in enumerate(test_data):
      print(str(x) + ' ' + color.rgb_hex_str(x))

Outcome:

10 #ff0000 - same
12 #ff0000 - same

17 #f80300
25 #e60c00
27 #cf1800
29 #c81b00
31 #c11f00
54 #a22e00
58 #6f4800
59 #664c00
61 #614f00
69 #4f5800
71 #415f00
72 #3c6100
86 #187400
87 #0d7900
90 #037e00
91 #008000

Is this a bug or am I missing something?

branca html popup not working

As the title states, the popup function is not working as of now. "branca.element.IFrame()" doesn't work while the older folium.element.IFrame() does. Attached is the screenshot.
branca

Is there a way to remove a child from a parent element?

In the past to remove an Element or MacroElement from its parent I used del parent._children[childName], but that seems a buggy operation.
In several cases when rendering the parent the child is still there.

Is there a preferred way to remove a child from a parent element?

An example of the issue I'm having:
Adding a Draw element to a Leaflet map using Folium
image

Parent has the draw_control child
image

JavaScript code injected to the resulting HTML element
image

Now I removed the child from the _children attribute using the method above:
image

The Draw element is still there when rendering!
image

and the JavaScript code is still there

Feature request: Log scale

From what I understand from the code, there is no log colormap. I will implement one locally for myself, please let me know if a PR would be appreciated.

Encountered issue finding the _cnames.json file when running as an executable

When I compile my script into an exe, when it is run, it throws an error that it cannot find the _cnames.json file. I verified that the file exists in the site-packages/branca folder, which is probably why the program runs fine in an IDE, but when the exe is created, it will end up looking for this file in a temp folder. I'm trying to figure out if there is a way to tell branca in my script where to look for this file so that it gets packaged with my exe or as another option, is in the same folder as my executable.

EDIT/UPDATE: In the colormap.py file, it has two absolute file references, one to '_cnames.json' and one to '_schemes.json' When the exe is created, it's looking in the temp folder, assuming it will be there. There must be some way to tell it to look in a relative path so that I can include those json files with my executable.

Uncaught TypeError: Cannot read property 'open' of null on branca==0.4 and above

Hi,

When using the following versions (branca==0.4, folium==0.12.1),

import folium 
folium.Map()

gives: Uncaught TypeError: Cannot read property 'open' of null

Downgrading to branca==0.3.1, folium==0.12.1 solves the problem, and the base map is rendered correctly.

Can anyone else replicate this error or know what might be the cause? I am working within a databricks notebook, on python 3.8.8.

ColorMaps do not support alpha

Dear all,

I encountered that the Colormap does not support rendering of the alpha values of the colors supplied. Is there a specific reason why the alpha channel is dropped?

I did a quick hack to propagate the alpha values to the rendering and it seems to work in my setup:
BalthasarSchachtner@ac70858

If you are interested in this feature, I can try to clean that up and to do a proper pull request.
Thanks for your work!

0.5.0: sphinx warnings `reference target not found`

First of all currently it is not possible to use straight sphinx-build command to build documentation out of source tree

+ /usr/bin/sphinx-build -n -T -b man docs/source build/sphinx/man
Running Sphinx v5.0.2

Traceback (most recent call last):
  File "/usr/lib/python3.8/site-packages/sphinx/config.py", line 343, in eval_config_file
    exec(code, namespace)
  File "/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/docs/source/conf.py", line 26, in <module>
    from branca._version import get_versions
ModuleNotFoundError: No module named 'branca'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/lib/python3.8/site-packages/sphinx/cmd/build.py", line 272, in build_main
    app = Sphinx(args.sourcedir, args.confdir, args.outputdir,
  File "/usr/lib/python3.8/site-packages/sphinx/application.py", line 202, in __init__
    self.config = Config.read(self.confdir, confoverrides or {}, self.tags)
  File "/usr/lib/python3.8/site-packages/sphinx/config.py", line 165, in read
    namespace = eval_config_file(filename, tags)
  File "/usr/lib/python3.8/site-packages/sphinx/config.py", line 356, in eval_config_file
    raise ConfigError(msg % traceback.format_exc()) from exc
sphinx.errors.ConfigError: There is a programmable error in your configuration file:

Traceback (most recent call last):
  File "/usr/lib/python3.8/site-packages/sphinx/config.py", line 343, in eval_config_file
    exec(code, namespace)
  File "/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/docs/source/conf.py", line 26, in <module>
    from branca._version import get_versions
ModuleNotFoundError: No module named 'branca'


Configuration error:
There is a programmable error in your configuration file:

Traceback (most recent call last):
  File "/usr/lib/python3.8/site-packages/sphinx/config.py", line 343, in eval_config_file
    exec(code, namespace)
  File "/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/docs/source/conf.py", line 26, in <module>
    from branca._version import get_versions
ModuleNotFoundError: No module named 'branca'

This can be fixed by patch like below:

--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -12,9 +12,9 @@
 # add these directories to sys.path here. If the directory is relative to the
 # documentation root, use os.path.abspath to make it absolute, like shown here.
 #
-# import os
-# import sys
-# sys.path.insert(0, os.path.abspath('.'))
+import os
+import sys
+sys.path.insert(0, os.path.abspath("../.."))


 # -- Project information -----------------------------------------------------

This patch fixes what is in the comment and that can of fix is suggested in sphinx example copy.py https://www.sphinx-doc.org/en/master/usage/configuration.html#example-of-
configuration-file

Than .. on building my packages I'm using sphinx-build command with -n switch which shows warmings about missing references. These are not critical issues.

+ /usr/bin/sphinx-build -n -T -b man docs/source build/sphinx/man
Running Sphinx v5.0.2
WARNING: Invalid configuration value found: 'language = None'. Update your configuration to a valid langauge code. Falling back to 'en' (English).
making output directory... done
WARNING: html_static_path entry '_static' does not exist
building [mo]: targets for 0 po files that are out of date
building [man]: all manpages
updating environment: [new config] 3 added, 0 changed, 0 removed
reading sources... [100%] index
looking for now-outdated files... none found
pickling environment... done
checking consistency... done
writing... python-branca.3 { element colormap } /home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.CssLink:: WARNING: py:class reference target not found: default False
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Div:: WARNING: py:class reference target not found: default '100%'
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Div:: WARNING: py:class reference target not found: default '100%'
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Div:: WARNING: py:class reference target not found: default '0%'
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Div:: WARNING: py:class reference target not found: default '0%'
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Div:: WARNING: py:class reference target not found: default 'relative'
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Element:: WARNING: py:class reference target not found: default None
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Element:: WARNING: py:class reference target not found: default None
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Element.save:: WARNING: py:class reference target not found: file object
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Element.save:: WARNING: py:class reference target not found: default True
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Figure:: WARNING: py:class reference target not found: default "100%"
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Figure:: WARNING: py:class reference target not found: default None
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Figure:: WARNING: py:class reference target not found: default "60%"
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Figure:: WARNING: py:class reference target not found: default None
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Figure:: WARNING: py:class reference target not found: tuple of two int
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Figure:: WARNING: py:class reference target not found: default None
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Figure.add_subplot:: WARNING: py:class reference target not found: >>>
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Figure.add_subplot:: WARNING: py:class reference target not found: # Create a div in the 5th cell of a 3rows x
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Figure.add_subplot:: WARNING: py:class reference target not found: grid
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Figure.add_subplot:: WARNING: py:class reference target not found: bottom-left
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Html:: WARNING: py:class reference target not found: default '100%'
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.Html:: WARNING: py:class reference target not found: default '100%'
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.IFrame:: WARNING: py:class reference target not found: default None
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.IFrame:: WARNING: py:class reference target not found: default "100%"
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.IFrame:: WARNING: py:class reference target not found: default None
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.IFrame:: WARNING: py:class reference target not found: default "60%"
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.IFrame:: WARNING: py:class reference target not found: tuple of two int
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.IFrame:: WARNING: py:class reference target not found: default None
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/element.py:docstring of branca.element.JavascriptLink:: WARNING: py:class reference target not found: default False
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.ColorMap:: WARNING: py:class reference target not found: default 10
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.LinearColormap:: WARNING: py:class reference target not found: list-like object with at least two colors.
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.LinearColormap:: WARNING: py:class reference target not found: list of floats
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.LinearColormap:: WARNING: py:class reference target not found: default None
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.LinearColormap:: WARNING: py:class reference target not found: default 0.
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.LinearColormap:: WARNING: py:class reference target not found: default 1.
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.LinearColormap:: WARNING: py:class reference target not found: default 10
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.LinearColormap.to_step:: WARNING: py:class reference target not found: default None
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.LinearColormap.to_step:: WARNING: py:class reference target not found: list of floats
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.LinearColormap.to_step:: WARNING: py:class reference target not found: default None
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.LinearColormap.to_step:: WARNING: py:class reference target not found: list of floats
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.LinearColormap.to_step:: WARNING: py:class reference target not found: default None
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.LinearColormap.to_step:: WARNING: py:class reference target not found: default 'linear'
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.LinearColormap.to_step:: WARNING: py:class reference target not found: list of floats
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.LinearColormap.to_step:: WARNING: py:class reference target not found: default None
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.LinearColormap.to_step:: WARNING: py:class reference target not found: default None
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.LinearColormap.to_step:: WARNING: py:class reference target not found: default 10
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.StepColormap:: WARNING: py:class reference target not found: list-like object
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.StepColormap:: WARNING: py:class reference target not found: list of floats
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.StepColormap:: WARNING: py:class reference target not found: default None
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.StepColormap:: WARNING: py:class reference target not found: default 0.
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.StepColormap:: WARNING: py:class reference target not found: default 1.
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.StepColormap:: WARNING: py:class reference target not found: default 10
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.StepColormap.to_linear:: WARNING: py:class reference target not found: list of floats
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.StepColormap.to_linear:: WARNING: py:class reference target not found: default None
/home/tkloczko/rpmbuild/BUILD/branca-0.5.0/branca/colormap.py:docstring of branca.colormap.StepColormap.to_linear:: WARNING: py:class reference target not found: default 10
done
build succeeded, 57 warnings.

You can peak on fixes that kind of issues in other projects
latchset/jwcrypto#289
click-contrib/sphinx-click@abc31069
latchset/jwcrypto#289
RDFLib/rdflib-sqlalchemy#95
sissaschool/elementpath@bf869d9e
jaraco/cssutils#21
pywbem/pywbem#2895
sissaschool/xmlschema@42ea98f2

Adding a custom colored background on a colorbar?

Is there an easy way to add a custom background to a colorbar (e.g. white) to make it more visible?

I would like to add a white rectangle frame below the colorbar . Being able to set the alpha for the frame background could also be nice...

image

Expose legend_scaler's max_labels in ColorMap

Hi,

I see that legend_scaler has an option to specify the number of labels (max_labels) but that is not accessible form within ColorMap.

Would be great to expose it in ColorMap.__init__ and then pass it to render. With large numbers you get overlaps and there's no way to prevent it.

Relevant bits:

def legend_scaler(legend_values, max_labels=10.0):

self.tick_labels = legend_scaler(self.index)

Happy to do a PR for that.

Version in `_version.py` incorrect

G'day, looks like there's an issue with the version being generated by setuptools when installing from the git repository.

It's creating versions starting with 0.1 instead of 0.7.

This makes it a lot harder to test its interaction with other libraries, as folium requires version 0.3.0 or higher.

When I was mistakenly using an outdated version of setuptools, I also got the message recommending:
migrating from the deprecated setup_requires mechanism to pep517/518
and using a pyproject.toml to declare build dependencies
which are reliably pre-installed before running the build tools

Saving with `pathlib` object

Would be nice if the save functionality worked with pathlib's PosixPath object.

No python requirements would have to change with pathlib being introduced in python 3.4

Seems like check would go here:

branca/branca/element.py

Lines 162 to 163 in 629ed34

if isinstance(outfile, str) or isinstance(outfile, bytes):
fid = open(outfile, 'wb')

rendering utf-8 with Iframe

Hi everyone,

When I put html in my popup on folium using the IFrame element, I got the following issue with utf-8 encoded text.
bad_folium_rendering
I tracked the issue and find that the charset was missing in the html part of the iframe, after I put it I got the expected result.
good_folium_rendering
I put my correction into the pull request below
#14

If that good for you I hope that it can be merged soon.

Regards

HTML Popup

I couldn't find a way of embedding Html in Popups without the use of iframes. Iframes are sometimes overkill for simple nested links or browser compatability issues so I create a HTMLPopup class for element.py. Would be great if you could add this it the master branch.

class HTMLPopup(Element):
    """Create a Figure object, to plot things into it.

    Parameters
    ----------
    html : str, default None
        Eventual HTML code that you want to put in the frame.
    width : str, default "100%"
        The width of the Figure.
        It may be a percentage or pixel value (like "300px").
    height : str, default None
        The height of the Figure.
        It may be a percentage or a pixel value (like "300px").
    ratio : str, default "60%"
        A percentage defining the aspect ratio of the Figure.
        It will be ignored if height is not None.
    figsize : tuple of two int, default None
        If you're a matplotlib addict, you can overwrite width and
        height. Values will be converted into pixels in using 60 dpi.
        For example figsize=(10, 5) will result in
        width="600px", height="300px".
    """
    def __init__(self, html=None, width="100%", height=None, ratio="60%",
                 figsize=None):
        super(HTMLPopup, self).__init__()
        self._name = 'HTMLPopup'

        self.width = width
        self.height = height
        self.ratio = ratio
        if figsize is not None:
            self.width = str(60*figsize[0])+'px'
            self.height = str(60*figsize[1])+'px'

        if isinstance(html, text_type) or isinstance(html, binary_type):
            self.add_children(Element(html))
        elif html is not None:
            self.add_children(html)

    def render(self, **kwargs):
        """Renders the HTML representation of the element."""
        html = super(HTMLPopup, self).render(**kwargs)
        html = html  # noqa

        if self.height is None:
            htmlpopup = (
            '<div style="width:{width};">'
            '<div style="position:relative;width:100%;height:0;padding-bottom:{ratio};">'  # noqa
            '{html}'
            '</div></div>').format
            htmlpopup = htmlpopup(html=html,
                            width=self.width,
                            ratio=self.ratio)
        else:
            htmlpopup = ('<div width="{width}" '
                      'height="{height}">{html}</div>').format
            htmlpopup = htmlpopup(html=html, width=self.width, height=self.height)
        return htmlpopup

Version control is off

I noticed two problems with version control:

  • There is no branch with the 0.2 release.
  • master version number 0.2, even though it has additional commits compared to the 0.2 release.

My suggestion would be to do it similarly as in folium, where each release has a branch and the master has a version number of e.g. 0.5.0+104.gbae5528. I suppose this was already the way it is supposed to be in branca.

Branca colormap caption with apostrophe makes map does not show

Describe the bug
When the caption of the colormap contains an apostrophe, the folium map does not show (I get a white rectangle)

To Reproduce

mymap= folium.Map(tiles = "Stamen Toner")

colormap = branca.colormap.LinearColormap(['red','yellow', 'green'], vmin=0.0, vmax=5.0)
colormap.caption = "Agency's rating"
colormap.add_to(mymap)

mymap

Expected behavior
The expected behavior is to get a folium map with red to green colormap having the caption "Agency's rating" but i got a white rectangle

Environment (please complete the following information):

  • Browser chrome and edge
  • Jupyter lab
  • Python version 3.9.10
  • folium version 0.12.1.post1
  • branca version 0.4.2

Additional context
The code works perfectly fine if the caption does not have an apostrophe.

Possible solutions
List any solutions you may have come up with.

folium is maintained by volunteers. Can you help making a fix for this issue?

Question about color support.

For Qualitative schemes, restrict number of colors to 6?

Is the any solution to support more color? as the Paired has 12 kinds of colors.

New release

It would be great if you all could cut a new release at some point. I spent some time debugging an incompatibility with the data-html attribute related to fastpages, but the new srcdoc approach looks simpler.

create an asymmetric colormap

I am trying to create a colormap for my data, like:

from branca.colormap import linear

colormap = linear.RdBu.scale(
    df.MyValue.min(),
    df.MyValue.max())

colormap

zoewh

Now what I want to achieve is to have the center of the colormap on the 0. I understand that I can convert this to step colormap like:

colormap = colormap.to_step(index=[-200, 0, 1200])

schermata 2017-12-16 alle 16 10 58

but it's not espressive in terms of values variation, only in terms of pos/neg values.

Is there a way to move the "center" of the colormap?

How to show latex caption?

from branca.colormap import linear

colormap_choice = linear.YlOrRd_04
vmin = 3.2
vmax = 10.3
colormap = colormap_choice.scale(vmin, vmax)
colormap.caption = '$\Delta$ x'
colormap
image

It seems the latex symbol $\Delta$ is neglected.

color_brewer raises KeyError if user requests more colors than what the colormap has

Problem
branca.utilities.color_brewer raises a non descriptive KeyError if the user requests more colors than the number of colors forming the selected colormap.

For example, RdYlBu is made of 11 individual colors. If the user requests more than 11 colors using the parameter n, this will trigger this error

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-8-32dd8f641e66> in <module>
      6 print(branca.utilities.color_brewer('RdYlBu', 11))
      7 
----> 8 print(branca.utilities.color_brewer('RdYlBu', 12))
      9 

~\Miniconda3\envs\houselossmodel\lib\site-packages\branca\utilities.py in color_brewer(color_code, n)
    150     if not explicit_scheme:
    151         # Check to make sure that it is not a qualitative scheme.
--> 152         if scheme_info[base_code] == 'Qualitative':
    153             matching_quals = []
    154             for key in schemes:

KeyError: 'RdYlBu'

Minimal code

import branca
print(branca.__version__)
# 0.4.2

print(branca.utilities.color_brewer('RdYlBu'))
# ['#d73027', '#fc8d59', '#fee090', '#e0f3f8', '#91bfdb', '#4575b4']
# defaults to n=6

print(branca.utilities.color_brewer('RdYlBu', 11))
# ['#a50026', '#d73027', '#f46d43', '#fdae61', '#fee090', '#ffffbf', '#e0f3f8', '#abd9e9', '#74add1', '#4575b4', '#313695']

print(branca.utilities.color_brewer('RdYlBu', 12))
# KeyError

Other comments
This issue is linked to python-visualization/folium#1270

My understanding is that color_brewer is not meant to generate more colors than what is available. For that we can use branca.utilities.linear_gradient.
However, there are two issues I can see with this behaviour:

  • The KeyError raised is non descriptive and does not point to the real problem
  • I cannot see a straightforward way to know how many colors a specific colormap has, or to automatically return the maximum number of colors of that colormap

`scheme_info` wrong copy pasta

A copy pasta to initialize the scheme_info variable make it wrong.

branca/branca/utilities.py

Lines 134 to 135 in 52b10bd

with open(os.path.join(rootpath, '_cnames.json')) as f:
scheme_info = json.loads(f.read())

The copy-paste is wrong, not because of "a bad name for a variable", but because the content loaded is not the expected one. The file _cnames.json does not embed the wanted information in the following line:

if scheme_info[base_code] == 'Qualitative':

Fix

Replace by the right file.

 with open(os.path.join(rootpath, 'scheme_info.json')) as f: 
     scheme_info = json.loads(f.read()) 

Other comment

It may fix #104, python-visualization/folium#1270, but not sure, I have not tested.

FileNotFoundError: [Errno 2] No such file or directory: '/home/keshav/Desktop/application/src/dist/main/branca/_cnames.json'

I was trying to get executable files of an application that uses folium to display maps. Folium inturn uses Branca.

This is the description of the system and OS I am using

  • Output of pyinstaller --version: 4
  • Version of Python: 3.8.5
  • Platform: Ubuntu 20.04.1 LTS

This is the minimal example of my application

import folium
print('hello world')

I tried the solutions suggested in pyinstaller/pyinstaller#4809 , https://groups.google.com/g/pyinstaller/c/OYhJdeZ9010/m/vLhYAWUzAQAJ,
and
pyinstaller/pyinstaller#5247

Confusing error when trying to create a LinearColormap with wrong arg type

Hi,

if max(color_tuple) > 1.:

This line raises an UnboundLocalError: local variable 'color_tuple' referenced before assignment when x is not an expected type, it's not very informative and makes it necessary to dig in the code to figure out the real problem.
Instead there should be an else clause that raises a ValueError of some sort to indicate x is not the right type.

Minimal example:

import seaborn as sns
import branca
my_palette = sns.color_palette(["#ffffff", "#000000"])
colorscale = branca.colormap.LinearColormap(*my_palette)

License type on pypi

I am not sure if it's appropriate to ask here. The license on Pypi says: "Copyright (C) 2013, Martin Journois". Since this is really open source freeware, could it be changed to something like BSD? My company scans all the pypi packages and this is blocked for download due to the license issue. Thank you.

Branca HTML iFrame width in percentage not working

When I am applying the width in percentage the popup is not working but when giving in the numbers it is working

    html = fancy_html(i)
    iframe = branca.element.IFrame(html=html,width='100%',height='40%',ratio='20%')
    popup = folium.Popup(iframe,parse_html=True)

when accessing with the width numbers value it is working

    html = fancy_html(i)
    iframe = branca.element.IFrame(html=html,width='200',height='40%',ratio='20%')
    popup = folium.Popup(iframe,parse_html=True)

Can't perform this operation for unregistered loader type

We are using branca in our application (ClimMob). We just integrated Pytest for our app and we are getting the below error while pytest collects the tests.

climmob/products/datacollectionprogress/celerytasks.py:9: in <module>
    import folium
<frozen importlib._bootstrap>:991: in _find_and_load
    ???
<frozen importlib._bootstrap>:975: in _find_and_load_unlocked
    ???
<frozen importlib._bootstrap>:671: in _load_unlocked
    ???
../env_py3ClimMob/lib/python3.8/site-packages/_pytest/assertion/rewrite.py:170: in exec_module
    exec(co, module.__dict__)
../env_py3ClimMob/lib/python3.8/site-packages/folium/__init__.py:5: in <module>
    import branca
<frozen importlib._bootstrap>:991: in _find_and_load
    ???
<frozen importlib._bootstrap>:975: in _find_and_load_unlocked
    ???
<frozen importlib._bootstrap>:671: in _load_unlocked
    ???
../env_py3ClimMob/lib/python3.8/site-packages/_pytest/assertion/rewrite.py:170: in exec_module
    exec(co, module.__dict__)
../env_py3ClimMob/lib/python3.8/site-packages/branca/__init__.py:1: in <module>
    import branca.colormap as colormap
<frozen importlib._bootstrap>:991: in _find_and_load
    ???
<frozen importlib._bootstrap>:975: in _find_and_load_unlocked
    ???
<frozen importlib._bootstrap>:671: in _load_unlocked
    ???
../env_py3ClimMob/lib/python3.8/site-packages/_pytest/assertion/rewrite.py:170: in exec_module
    exec(co, module.__dict__)
../env_py3ClimMob/lib/python3.8/site-packages/branca/colormap.py:62: in <module>
    class ColorMap(MacroElement):
../env_py3ClimMob/lib/python3.8/site-packages/branca/colormap.py:74: in ColorMap
    _template = ENV.get_template('color_scale.js')
../env_py3ClimMob/lib/python3.8/site-packages/jinja2/environment.py:883: in get_template
    return self._load_template(name, self.make_globals(globals))
../env_py3ClimMob/lib/python3.8/site-packages/jinja2/environment.py:857: in _load_template
    template = self.loader.load(self, name, globals)
../env_py3ClimMob/lib/python3.8/site-packages/jinja2/loaders.py:115: in load
    source, filename, uptodate = self.get_source(environment, name)
../env_py3ClimMob/lib/python3.8/site-packages/jinja2/loaders.py:248: in get_source
    if not self.provider.has_resource(p):
../env_py3ClimMob/lib/python3.8/site-packages/pkg_resources/__init__.py:1404: in has_resource
    return self._has(self._fn(self.module_path, resource_name))
../env_py3ClimMob/lib/python3.8/site-packages/pkg_resources/__init__.py:1472: in _has
    raise NotImplementedError(
E   NotImplementedError: Can't perform this operation for unregistered loader type

Any idea is appreciated.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.