本文介绍了覆盖Nd覆盖,同时保持颜色/更改标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个不同类型的资产"散点图,每个资产应具有相同的颜色并在图例中进行标记.我可以使用Scatter的NdOverlay做到这一点.然后,我想覆盖两个这样的图,例如一个来自模型,另一个来自实验,以便第一个和第二个标记仅发生变化,但每种资产保持相同的颜色.

I want a scatter plot of different types of "asset", each asset should have the same color and labeled in the legend. I can do this using an NdOverlay of Scatter. Then I want to overlay two such plots, eg one coming from a model and another from experiment, so that the first and second only change in marker but keeps the same color for each asset.

我希望它能起作用

df1 = pd.DataFrame({"asset": ["A", "B", "B"], "x": [1,2,3], "y": [1,2,3]})
df2 = pd.DataFrame({"asset": ["A", "B", "B"], "x": [1.5,2.5,3.5], "y": [1,2,3]})
df1.hvplot.scatter(x="x", y="y", by="asset") * df2.hvplot.scatter(x="x", y="y", by="asset").opts({"Scatter": {"style": {"marker": "d"}}})

,但每个资产df1.hvplot中的颜色与df2.hvplot中的颜色不同.我想从df1和df2开始最简洁的方法.

but the colors in df1.hvplot per asset are different to those of df2.hvplot. I would like the most concise way starting from df1 and df2.

是否有一个简单的解决方案,我不必考虑df1和df2的排序,也不必考虑它们是否具有完全相同的资产"集.例如,我需要一些可以配合使用的东西

Is there a simple solution where I do not have to think about the sorting of df1 and df2 or whether they have the exact same set of "assets". Eg, I need something that would also work with

df1 = pd.DataFrame({"asset": ["A", "B", "B"], "x": [1,2,3], "y": [1,2,3]})
df2 = pd.DataFrame({"asset": ["C", "B", "A"], "x": [1.5,2.5,3.5], "y": [1,2,3]})
l1=df1.hvplot.scatter(x="x", y="y", by="asset")
l2=df2.hvplot.scatter(x="x", y="y", by="asset").opts(hv.opts.Scatter(marker='d'))
ll=l1*l2

df1 = pd.DataFrame({"asset": ["A", "B", "B"], "x": [1,2,3], "y": [1,2,3]})
df2 = pd.DataFrame({"asset": ["A", "B", "B", "C"], "x": [1.5,2.5,3.5, 4], "y": [1,2,3, 1]})
l1=df1.hvplot.scatter(x="x", y="y", by="asset")
l2=df2.hvplot.scatter(x="x", y="y", by="asset").opts(hv.opts.Scatter(marker='d'))
ll=l1*l2

推荐答案

如果需要更大的灵活性,则有两种选择:

If you need more flexibility, there are two options:

  1. 设置尺寸容器的样式,
  2. 使用附加值维度进行样式设置.

有关更多信息,请参见此处: jupyter notebook github存储库,但是代码是这样的.

For more information, see here: jupyter notebook, github repo, but the code goes like this.

选项1(更详细,但如果您始终在类似HoloMap的容器中工作,通常会更容易):

Option 1 (more verbose, but often easier if you are working in a HoloMap-like container anyway):

import holoviews as hv
from holoviews import opts, dim
hv.extension('bokeh')
import pandas as pd
import numpy as np

def cycle_kdim_opts(layout, kdim_opts):
    """
    For each given kdim of an Nd holoviews container, create an options dict
    that can be passed into a holoviews `opts` object.

    Parameters
    ----------
    layout : A holoviews Nd container (HoloMap, ...)
    kdim_opts : dict of the form {kdim: {style_option: [alternatives]}}
        For an example, see below.


    """
    # Output shown for:
    # kdim_opts = {
    #     'h': {'color': ['orange', 'cyan']},
    #     'g': {'size': [30, 10]},
    # }
    values = {kd.name: list(d) for kd, d in zip(layout.kdims, zip(*layout.data.keys()))}
    # print(values)
    # {'g': ['a', 'b', 'b'], 'h': ['d', 'c', 'd']}

    mapping = {}
    for kd, o in kdim_opts.items():
        unique_values = list(set(values[kd]))
        styles = list(o.values())[0]
        mapping[kd] = dict(zip(unique_values, styles))
    # print(mapping)
    # {'h': {'c': 'orange', 'd': 'cyan'}, 'g': {'b': 30, 'a': 10}}

    kdim2style = {k: list(v.keys())[0] for k, v in kdim_opts.items()}
    # print(kdim2style)
    # {'h': 'color', 'g': 'size'}

    mapped_styles = {kdim2style[kd]: hv.Cycle([mapping[kd][value] for value in values])
                     for kd, values in values.items()}
    # print(mapped_styles)
    # {'size': Cycle(['10', '30', '30']), 'color': Cycle(['cyan', 'orange', 'cyan'])}

    return mapped_styles

df1 = pd.DataFrame({'asset': ['A', 'B', 'B'], 'x': [1.,2.,3.], 'y': [1.,2.,3.]})
df2 = pd.DataFrame({'asset': ['A', 'B', 'B', 'C'], 'x': [1.5,2.5,3.5,4], 'y': [1.,2.,3.,1.]})
df = df1.assign(source='exp').merge(df2.assign(source='mod'), how='outer')

labels = hv.Labels(df.assign(l=df.asset+',\n'+df.source), ['x', 'y'], 'l')

l = hv.Dataset(df, ['x', 'y', 'asset', 'source',], []).to(hv.Points).overlay()

od = {
    'source': {'size': [30, 10]},
    'asset': {'color': ['orange', 'cyan', 'yellow']},
}

options = (
    opts.NdOverlay(legend_position='right', show_legend=True, width=500),
    opts.Points(padding=.5, show_title=False, title_format='',
                toolbar=None, **cycle_kdim_opts(l, od)),
)

l.opts(*options) * labels

选项2:方法较为冗长,但需要付出更多的努力,例如稍后自定义图例.

Option 2: Way less verbose, but takes more effort to e.g. customize the legend later on.

df1 = pd.DataFrame({'asset': ['A', 'B', 'B'], 'x': [1.,2.,3.], 'y': [1.,2.,3.]})
df2 = pd.DataFrame({'asset': ['A', 'B', 'B', 'C'], 'x': [1.5,2.5,3.5,4], 'y': [1.,2.,3.,1.]})
df = df1.assign(source='exp').merge(df2.assign(source='mod'), how='outer')

labels = hv.Labels(df.assign(l=df.asset+',\n'+df.source), ['x', 'y'], 'l')

l = hv.Points(df, ['x', 'y'], ['asset', 'source',])

options = (
    opts.NdOverlay(legend_position='right', show_legend=True, width=500),
    opts.Points(padding=.5, show_title=False, show_legend=True,
                marker=dim('source').categorize({'exp':'circle', 'mod':'diamond'}),
                color=dim('asset').categorize({'A':'orange', 'B':'cyan', 'C':'yellow'}),
                size=10, toolbar=None)
)

l.opts(*options) * labels

原始建议(最接近您的示例):您可以例如使用hv.Cycle对象明确设置颜色:

Original suggestion (closest to your example):You could e.g. explicitly set the colours using a hv.Cycle object:

df1 = pd.DataFrame({"asset": ["A", "B", "B"], "x": [1,2,3], "y": [1,2,3]})
df2 = pd.DataFrame({"asset": ["A", "B", "B"], "x": [1.5,2.5,3.5], "y": [1,2,3]})
l1=df1.hvplot.scatter(x="x", y="y", by="asset")
l2=df2.hvplot.scatter(x="x", y="y", by="asset").opts(hv.opts.Scatter(marker='d'))
ll=l1*l2
ll.opts(hv.opts.Scatter(padding=.1, color=hv.Cycle(['blue', 'orange'])))

这篇关于覆盖Nd覆盖,同时保持颜色/更改标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 04:04