为了账号安全,请及时绑定邮箱和手机立即绑定

当“整洁的数据”不是问题时,如何在plotnine中为多条曲线添加图例

当“整洁的数据”不是问题时,如何在plotnine中为多条曲线添加图例

郎朗坤 2023-09-19 14:02:17
有几个人询问,当曲线因选择要绘制的行而不同时,如何在多条曲线中添加图例ggplot2或为多条曲线添加图例。plotnine典型的答案是将数据重新格式化为整齐的数据。一些示例位于此处、此处和此处。我需要多行不是因为对数据进行子集化,而是因为我想比较平滑方法。所有线路的数据都相同,因此上述答案没有帮助。后两个答案指出,在R 中,可以通过将说明符移动到内部ggplot2来创建图例。这里详细描述了这一点,这与我想要做的类似。coloraes(...)这也应该起作用plotnine吗?我尝试了一个类似于上一个链接的示例。没有图例它工作正常:from plotnine import *from plotnine.data import *(ggplot(faithful, aes(x='waiting'))    + geom_line(stat='density', adjust=0.5, color='red')    + geom_line(stat='density', color='blue')    + geom_line(stat='density', adjust=2, color='green')    + labs(title='Effect of varying KDE smoothing parameter',           x='Time to next eruption (min)',           y='Density'))但当我为了获得传奇color而进入时,它失败了:aesfrom plotnine import *from plotnine.data import *(ggplot(faithful, aes(x='waiting'))    + geom_line(aes(color='red'), stat='density', adjust=0.5)    + geom_line(aes(color='blue'), stat='density')    + geom_line(aes(color='green'), stat='density', adjust=2)    + labs(title='Effect of varying KDE smoothing parameter',           x='Time to next eruption (min)',           y='Density')    + scale_color_identity(guide='legend'))这给出了错误 PlotnineError: "Could not evaluate the 'color' mapping: 'red' (original error: name 'red' is not defined)"。关于如何添加图例有什么建议吗?谢谢。
查看完整描述

2 回答

?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

看起来您发布的最后一个链接是在正确的轨道上,但您必须欺骗 python 来克服 R 所做的一些非标准评估。我可以通过在颜色名称周围设置两组引号来使其工作:


(ggplot(faithful, aes(x='waiting'))

    + geom_line(aes(color="'red'"), stat='density', adjust=0.5)

    + geom_line(aes(color="'blue'"), stat='density')

    + geom_line(aes(color="'green'"), stat='density', adjust=2)

    + labs(title='Effect of ...',

           x='Time to next eruption (min)',

           y='Density')

    + scale_color_identity(guide='legend',name='My color legend')

)

1

您可以制作自己的标签,例如帖子:


(ggplot(faithful,aes(x='waiting'))

 + geom_line(aes(color="'red'"),stat='density',adjust=.5)

 + geom_line(aes(color="'blue'"),stat='density')

 + geom_line(aes(color="'green'"), stat='density',adjust=2)

 +labs(title='Effect of ...',x='Time to next eruption (min)',

       y='Density')

 + scale_color_identity(guide='legend',name='My colors',

                        breaks=['red','blue','green'],

                        labels=['Label 1','Label 2','Label 3']))

2


查看完整回答
反对 回复 2023-09-19
?
FFIVE

TA贡献1797条经验 获得超6个赞

将颜色放在引号中,例如'"red"'而不是'red'。


(ggplot(faithful, aes(x='waiting'))

    + geom_line(aes(color='"red"'), stat='density', adjust=0.5)

    + geom_line(aes(color='"blue"'), stat='density')

    + geom_line(aes(color='"green"'), stat='density', adjust=2)

    + labs(title='Effect of varying KDE smoothing parameter',

           x='Time to next eruption (min)',

           y='Density')

    + scale_color_identity(guide='legend')

)


查看完整回答
反对 回复 2023-09-19
  • 2 回答
  • 0 关注
  • 122 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信