Changing colormap for categorical data in Holoviews/Datashader





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I'm trying to visualize categorical spatial data using Datashader and Holoviews, similarly to https://anaconda.org/jbednar/census-hv-dask/notebook. However, when I try to assign different colors to categories, I always end up with same (presumably default) colors (An example of the output image.)



Here is the code I'm running in Jupyter notebook. Could anyone advise me on how to make the custom color map work? Or at least run the code to see if you end up with colors matching the legend or not. Thank you!



from sklearn.datasets.samples_generator import make_blobs
from matplotlib import pyplot
import pandas as pd

import holoviews as hv
import geoviews as gv
import datashader as ds
from cartopy import crs
from matplotlib.cm import get_cmap
from holoviews.operation.datashader import datashade, aggregate
hv.notebook_extension('bokeh', width=95)

# Generating blob data:
X, y = make_blobs(n_samples=5000000, centers=5, n_features=2)
df = pd.DataFrame(dict(x=X[:,0], y=X[:,1], label=y))

# Plotting the blobs using datashader and holoviews:
%opts Overlay [width=800 height=455 xaxis=None yaxis=None show_grid=False]
%opts Shape (fill_color=None line_width=1.5) [apply_ranges=False]
%opts Points [apply_ranges=False] WMTS (alpha=0.5) NdOverlay [tools=['tap']]

color_key = {0:'red', 1:'blue', 2:'green', 3:'yellow', 4:'black'}
labels = {0:'red', 1:'blue', 2:'green', 3:'yellow', 4:'black'}

color_points = hv.NdOverlay({labels[k]: gv.Points([0,0], crs=crs.PlateCarree(),
label=labels[k])(style=dict(color=v))
for k, v in color_key.items()})

dataset = gv.Dataset(df, kdims=['x', 'y'], vdims=['label'])
shaded = datashade(hv.Points(dataset), cmap=color_key, aggregator=ds.count_cat('label'))

shaded * color_points









share|improve this question































    1















    I'm trying to visualize categorical spatial data using Datashader and Holoviews, similarly to https://anaconda.org/jbednar/census-hv-dask/notebook. However, when I try to assign different colors to categories, I always end up with same (presumably default) colors (An example of the output image.)



    Here is the code I'm running in Jupyter notebook. Could anyone advise me on how to make the custom color map work? Or at least run the code to see if you end up with colors matching the legend or not. Thank you!



    from sklearn.datasets.samples_generator import make_blobs
    from matplotlib import pyplot
    import pandas as pd

    import holoviews as hv
    import geoviews as gv
    import datashader as ds
    from cartopy import crs
    from matplotlib.cm import get_cmap
    from holoviews.operation.datashader import datashade, aggregate
    hv.notebook_extension('bokeh', width=95)

    # Generating blob data:
    X, y = make_blobs(n_samples=5000000, centers=5, n_features=2)
    df = pd.DataFrame(dict(x=X[:,0], y=X[:,1], label=y))

    # Plotting the blobs using datashader and holoviews:
    %opts Overlay [width=800 height=455 xaxis=None yaxis=None show_grid=False]
    %opts Shape (fill_color=None line_width=1.5) [apply_ranges=False]
    %opts Points [apply_ranges=False] WMTS (alpha=0.5) NdOverlay [tools=['tap']]

    color_key = {0:'red', 1:'blue', 2:'green', 3:'yellow', 4:'black'}
    labels = {0:'red', 1:'blue', 2:'green', 3:'yellow', 4:'black'}

    color_points = hv.NdOverlay({labels[k]: gv.Points([0,0], crs=crs.PlateCarree(),
    label=labels[k])(style=dict(color=v))
    for k, v in color_key.items()})

    dataset = gv.Dataset(df, kdims=['x', 'y'], vdims=['label'])
    shaded = datashade(hv.Points(dataset), cmap=color_key, aggregator=ds.count_cat('label'))

    shaded * color_points









    share|improve this question



























      1












      1








      1








      I'm trying to visualize categorical spatial data using Datashader and Holoviews, similarly to https://anaconda.org/jbednar/census-hv-dask/notebook. However, when I try to assign different colors to categories, I always end up with same (presumably default) colors (An example of the output image.)



      Here is the code I'm running in Jupyter notebook. Could anyone advise me on how to make the custom color map work? Or at least run the code to see if you end up with colors matching the legend or not. Thank you!



      from sklearn.datasets.samples_generator import make_blobs
      from matplotlib import pyplot
      import pandas as pd

      import holoviews as hv
      import geoviews as gv
      import datashader as ds
      from cartopy import crs
      from matplotlib.cm import get_cmap
      from holoviews.operation.datashader import datashade, aggregate
      hv.notebook_extension('bokeh', width=95)

      # Generating blob data:
      X, y = make_blobs(n_samples=5000000, centers=5, n_features=2)
      df = pd.DataFrame(dict(x=X[:,0], y=X[:,1], label=y))

      # Plotting the blobs using datashader and holoviews:
      %opts Overlay [width=800 height=455 xaxis=None yaxis=None show_grid=False]
      %opts Shape (fill_color=None line_width=1.5) [apply_ranges=False]
      %opts Points [apply_ranges=False] WMTS (alpha=0.5) NdOverlay [tools=['tap']]

      color_key = {0:'red', 1:'blue', 2:'green', 3:'yellow', 4:'black'}
      labels = {0:'red', 1:'blue', 2:'green', 3:'yellow', 4:'black'}

      color_points = hv.NdOverlay({labels[k]: gv.Points([0,0], crs=crs.PlateCarree(),
      label=labels[k])(style=dict(color=v))
      for k, v in color_key.items()})

      dataset = gv.Dataset(df, kdims=['x', 'y'], vdims=['label'])
      shaded = datashade(hv.Points(dataset), cmap=color_key, aggregator=ds.count_cat('label'))

      shaded * color_points









      share|improve this question
















      I'm trying to visualize categorical spatial data using Datashader and Holoviews, similarly to https://anaconda.org/jbednar/census-hv-dask/notebook. However, when I try to assign different colors to categories, I always end up with same (presumably default) colors (An example of the output image.)



      Here is the code I'm running in Jupyter notebook. Could anyone advise me on how to make the custom color map work? Or at least run the code to see if you end up with colors matching the legend or not. Thank you!



      from sklearn.datasets.samples_generator import make_blobs
      from matplotlib import pyplot
      import pandas as pd

      import holoviews as hv
      import geoviews as gv
      import datashader as ds
      from cartopy import crs
      from matplotlib.cm import get_cmap
      from holoviews.operation.datashader import datashade, aggregate
      hv.notebook_extension('bokeh', width=95)

      # Generating blob data:
      X, y = make_blobs(n_samples=5000000, centers=5, n_features=2)
      df = pd.DataFrame(dict(x=X[:,0], y=X[:,1], label=y))

      # Plotting the blobs using datashader and holoviews:
      %opts Overlay [width=800 height=455 xaxis=None yaxis=None show_grid=False]
      %opts Shape (fill_color=None line_width=1.5) [apply_ranges=False]
      %opts Points [apply_ranges=False] WMTS (alpha=0.5) NdOverlay [tools=['tap']]

      color_key = {0:'red', 1:'blue', 2:'green', 3:'yellow', 4:'black'}
      labels = {0:'red', 1:'blue', 2:'green', 3:'yellow', 4:'black'}

      color_points = hv.NdOverlay({labels[k]: gv.Points([0,0], crs=crs.PlateCarree(),
      label=labels[k])(style=dict(color=v))
      for k, v in color_key.items()})

      dataset = gv.Dataset(df, kdims=['x', 'y'], vdims=['label'])
      shaded = datashade(hv.Points(dataset), cmap=color_key, aggregator=ds.count_cat('label'))

      shaded * color_points






      python colormap holoviews datashader






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 3 at 18:15







      Runkles

















      asked Jan 3 at 16:50









      RunklesRunkles

      686




      686
























          1 Answer
          1






          active

          oldest

          votes


















          0














          That code doesn't seem to be runnable (races is not defined, and gv is not imported), but in any case, categorical colors are determined by the color_key argument, not cmap, so you'd need to change cmap=color_key to color_key=color_key.






          share|improve this answer
























          • Thank you James, that solved my problem, I also edited the code to be runnable. I have just one more question: in your example notebook (link above in my original question) you are also using the cmap argument instead of color_key argument (when defining "shaded"), but the colors are right. How is this different to my case?

            – Runkles
            Jan 3 at 18:29











          • Ah, that's the real problem here! That link points to an old copy of the notebook that's been sitting around from before we had a way to show notebooks in the actual web site. There used to be only one way to set colormaps, but we split the color key and cmap options because categorical plots don't work well with the default cmap colormaps, but that copy of the notebook hasn't been updated. Plus we're about to move the examples into pyviz.org so that we can actually manage to maintain them. Sorry for the confusion, and I guess I should at least upload an updated nb there.

            – James A. Bednar
            Jan 4 at 3:55











          • Right, I will be using the notebooks in the actual web site for the reference from now on. Thanks again!

            – Runkles
            Jan 4 at 9:19











          • Turns out that census_hv_dask was a very old copy of the "gerrymandering" notebook now available at datashader.org, so I've deleted it to avoid confusion.

            – James A. Bednar
            Jan 16 at 15:23












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54026510%2fchanging-colormap-for-categorical-data-in-holoviews-datashader%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          That code doesn't seem to be runnable (races is not defined, and gv is not imported), but in any case, categorical colors are determined by the color_key argument, not cmap, so you'd need to change cmap=color_key to color_key=color_key.






          share|improve this answer
























          • Thank you James, that solved my problem, I also edited the code to be runnable. I have just one more question: in your example notebook (link above in my original question) you are also using the cmap argument instead of color_key argument (when defining "shaded"), but the colors are right. How is this different to my case?

            – Runkles
            Jan 3 at 18:29











          • Ah, that's the real problem here! That link points to an old copy of the notebook that's been sitting around from before we had a way to show notebooks in the actual web site. There used to be only one way to set colormaps, but we split the color key and cmap options because categorical plots don't work well with the default cmap colormaps, but that copy of the notebook hasn't been updated. Plus we're about to move the examples into pyviz.org so that we can actually manage to maintain them. Sorry for the confusion, and I guess I should at least upload an updated nb there.

            – James A. Bednar
            Jan 4 at 3:55











          • Right, I will be using the notebooks in the actual web site for the reference from now on. Thanks again!

            – Runkles
            Jan 4 at 9:19











          • Turns out that census_hv_dask was a very old copy of the "gerrymandering" notebook now available at datashader.org, so I've deleted it to avoid confusion.

            – James A. Bednar
            Jan 16 at 15:23
















          0














          That code doesn't seem to be runnable (races is not defined, and gv is not imported), but in any case, categorical colors are determined by the color_key argument, not cmap, so you'd need to change cmap=color_key to color_key=color_key.






          share|improve this answer
























          • Thank you James, that solved my problem, I also edited the code to be runnable. I have just one more question: in your example notebook (link above in my original question) you are also using the cmap argument instead of color_key argument (when defining "shaded"), but the colors are right. How is this different to my case?

            – Runkles
            Jan 3 at 18:29











          • Ah, that's the real problem here! That link points to an old copy of the notebook that's been sitting around from before we had a way to show notebooks in the actual web site. There used to be only one way to set colormaps, but we split the color key and cmap options because categorical plots don't work well with the default cmap colormaps, but that copy of the notebook hasn't been updated. Plus we're about to move the examples into pyviz.org so that we can actually manage to maintain them. Sorry for the confusion, and I guess I should at least upload an updated nb there.

            – James A. Bednar
            Jan 4 at 3:55











          • Right, I will be using the notebooks in the actual web site for the reference from now on. Thanks again!

            – Runkles
            Jan 4 at 9:19











          • Turns out that census_hv_dask was a very old copy of the "gerrymandering" notebook now available at datashader.org, so I've deleted it to avoid confusion.

            – James A. Bednar
            Jan 16 at 15:23














          0












          0








          0







          That code doesn't seem to be runnable (races is not defined, and gv is not imported), but in any case, categorical colors are determined by the color_key argument, not cmap, so you'd need to change cmap=color_key to color_key=color_key.






          share|improve this answer













          That code doesn't seem to be runnable (races is not defined, and gv is not imported), but in any case, categorical colors are determined by the color_key argument, not cmap, so you'd need to change cmap=color_key to color_key=color_key.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 3 at 17:11









          James A. BednarJames A. Bednar

          96636




          96636













          • Thank you James, that solved my problem, I also edited the code to be runnable. I have just one more question: in your example notebook (link above in my original question) you are also using the cmap argument instead of color_key argument (when defining "shaded"), but the colors are right. How is this different to my case?

            – Runkles
            Jan 3 at 18:29











          • Ah, that's the real problem here! That link points to an old copy of the notebook that's been sitting around from before we had a way to show notebooks in the actual web site. There used to be only one way to set colormaps, but we split the color key and cmap options because categorical plots don't work well with the default cmap colormaps, but that copy of the notebook hasn't been updated. Plus we're about to move the examples into pyviz.org so that we can actually manage to maintain them. Sorry for the confusion, and I guess I should at least upload an updated nb there.

            – James A. Bednar
            Jan 4 at 3:55











          • Right, I will be using the notebooks in the actual web site for the reference from now on. Thanks again!

            – Runkles
            Jan 4 at 9:19











          • Turns out that census_hv_dask was a very old copy of the "gerrymandering" notebook now available at datashader.org, so I've deleted it to avoid confusion.

            – James A. Bednar
            Jan 16 at 15:23



















          • Thank you James, that solved my problem, I also edited the code to be runnable. I have just one more question: in your example notebook (link above in my original question) you are also using the cmap argument instead of color_key argument (when defining "shaded"), but the colors are right. How is this different to my case?

            – Runkles
            Jan 3 at 18:29











          • Ah, that's the real problem here! That link points to an old copy of the notebook that's been sitting around from before we had a way to show notebooks in the actual web site. There used to be only one way to set colormaps, but we split the color key and cmap options because categorical plots don't work well with the default cmap colormaps, but that copy of the notebook hasn't been updated. Plus we're about to move the examples into pyviz.org so that we can actually manage to maintain them. Sorry for the confusion, and I guess I should at least upload an updated nb there.

            – James A. Bednar
            Jan 4 at 3:55











          • Right, I will be using the notebooks in the actual web site for the reference from now on. Thanks again!

            – Runkles
            Jan 4 at 9:19











          • Turns out that census_hv_dask was a very old copy of the "gerrymandering" notebook now available at datashader.org, so I've deleted it to avoid confusion.

            – James A. Bednar
            Jan 16 at 15:23

















          Thank you James, that solved my problem, I also edited the code to be runnable. I have just one more question: in your example notebook (link above in my original question) you are also using the cmap argument instead of color_key argument (when defining "shaded"), but the colors are right. How is this different to my case?

          – Runkles
          Jan 3 at 18:29





          Thank you James, that solved my problem, I also edited the code to be runnable. I have just one more question: in your example notebook (link above in my original question) you are also using the cmap argument instead of color_key argument (when defining "shaded"), but the colors are right. How is this different to my case?

          – Runkles
          Jan 3 at 18:29













          Ah, that's the real problem here! That link points to an old copy of the notebook that's been sitting around from before we had a way to show notebooks in the actual web site. There used to be only one way to set colormaps, but we split the color key and cmap options because categorical plots don't work well with the default cmap colormaps, but that copy of the notebook hasn't been updated. Plus we're about to move the examples into pyviz.org so that we can actually manage to maintain them. Sorry for the confusion, and I guess I should at least upload an updated nb there.

          – James A. Bednar
          Jan 4 at 3:55





          Ah, that's the real problem here! That link points to an old copy of the notebook that's been sitting around from before we had a way to show notebooks in the actual web site. There used to be only one way to set colormaps, but we split the color key and cmap options because categorical plots don't work well with the default cmap colormaps, but that copy of the notebook hasn't been updated. Plus we're about to move the examples into pyviz.org so that we can actually manage to maintain them. Sorry for the confusion, and I guess I should at least upload an updated nb there.

          – James A. Bednar
          Jan 4 at 3:55













          Right, I will be using the notebooks in the actual web site for the reference from now on. Thanks again!

          – Runkles
          Jan 4 at 9:19





          Right, I will be using the notebooks in the actual web site for the reference from now on. Thanks again!

          – Runkles
          Jan 4 at 9:19













          Turns out that census_hv_dask was a very old copy of the "gerrymandering" notebook now available at datashader.org, so I've deleted it to avoid confusion.

          – James A. Bednar
          Jan 16 at 15:23





          Turns out that census_hv_dask was a very old copy of the "gerrymandering" notebook now available at datashader.org, so I've deleted it to avoid confusion.

          – James A. Bednar
          Jan 16 at 15:23




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54026510%2fchanging-colormap-for-categorical-data-in-holoviews-datashader%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

          ts Property 'filter' does not exist on type '{}'

          mat-slide-toggle shouldn't change it's state when I click cancel in confirmation window