首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >合并`plotnine`图例中的颜色和形状

合并`plotnine`图例中的颜色和形状
EN

Stack Overflow用户
提问于 2021-01-22 12:22:36
回答 1查看 168关注 0票数 0

如何将color九的图例中的颜色和形状合并?这在R中似乎是可能的,但我不能让它在情节9中工作...

这里有一个例子:

代码语言:javascript
复制
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

在图9中,这是可能的吗?任何帮助都是非常感谢的!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-23 08:03:57

下面是对第二个链接中答案的python改编

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

代码语言:javascript
复制
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')
)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65839255

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档