【问题标题】:merge color and shape in `plotnine` legend在“plotnine”图例中合并颜色和形状
【发布时间】:2021-01-22 04:22:35
【问题描述】:

如何才能在plotnine的传说中融合颜色和形状? 在 R 中似乎是可能的。但我无法让它在 plotnine 中工作......

这是一个例子:

from plotnine import ggplot, geom_point, aes, stat_smooth, facet_wrap
from plotnine.data import mtcars

(
    ggplot(mtcars, aes('cyl', 'mpg', color='factor(gear)', shape='factor(vs)'))
     + geom_jitter()
)

这将创建以下图表:

我想在传说中将装备和 vs 结合起来。 所以红色圆圈表示齿轮= 3,vs = 0;红色三角形表示 齿轮 = 3,vs = 1;等等

...就像在 以下关于 R 的帖子:

How to merge color, line style and shape legends in ggplot

Combine legends for color and shape into a single legend

这在plotnine中可能吗?非常感谢任何帮助!

【问题讨论】:

    标签: python r ggplot2 plotnine


    【解决方案1】:

    这是您第二个链接中答案的python改编版

    如果要更改图例名称,则必须在 scale_*_manual 两个函数中使用 name 参数。

    from plotnine import ggplot, geom_point, aes, stat_smooth, facet_wrap,geom_jitter
    from plotnine.data import mtcars
    import plotnine as p9
    
    # add a column that combines the two columns
    new_mtcars = mtcars
    new_mtcars['legend_col'] = ['Gear: {} Vs: {}'.format(gear,vs)
                                for gear,vs in zip(new_mtcars.gear,mtcars.vs)]
    
    # specify dicts to use for determining colors and shapes
    gear_colors = {3:'red',4:'blue',5:'gray'}
    vs_shapes = {0:'^',1:'o'}
    
    # make the plot with scale_*_manual based on the gear and vs values
    (
        ggplot(mtcars, aes('cyl', 'mpg', color='legend_col', shape='legend_col'))
         + geom_jitter()
         + p9.scale_color_manual(values=[[gear_colors[i] for i in list(new_mtcars.gear.unique())
                                          if 'Gear: {}'.format(i) in label][0]
                                         for label in new_mtcars.legend_col.unique()],
                                 labels = list(new_mtcars.legend_col.unique()),
                                 name='My legend name')
         + p9.scale_shape_manual(values=[[vs_shapes[i] for i in list(new_mtcars.vs.unique())
                                          if 'Vs: {}'.format(i) in label][0]
                                         for label in new_mtcars.legend_col.unique()],
                                 labels = list(new_mtcars.legend_col.unique()),
                                 name='My legend name')
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-30
      • 2022-11-27
      • 1970-01-01
      • 2022-09-27
      • 2016-07-13
      • 2011-12-18
      • 2020-11-24
      相关资源
      最近更新 更多