问题描述
当曲线因要绘制的行的选择而不同时,几个人问过如何在ggplot2
或plotnine
中为多个曲线添加图例。典型的答案是将数据重新格式化为tidy data。一些示例为here,here和here。
我需要多行不是因为子集数据,而是因为我想比较平滑方法。所有行的数据都是相同的,因此上述答案无济于事。
后两个答案指出,在R的ggplot2
中,可以通过在color
内移动aes(...)
指定符来创建图例。 here对此进行了详细说明,与我想做的类似。
这也应该在plotnine
中起作用吗?我尝试了一个类似于previous link的示例。没有图例就可以正常工作:
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
移到aes
以获得图例时,它失败了:
from 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'),adjust=2)
+ labs(title='Effect of varying KDE smoothing parameter',y='Density')
+ scale_color_identity(guide='legend')
)
这给了错误
PlotnineError: "Could not evaluate the 'color' mapping: 'red' (original error: name 'red' is not defined)"
。
关于如何添加图例的任何建议?谢谢。
解决方法
将颜色放在引号中,例如用'"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"'),adjust=2)
+ labs(title='Effect of varying KDE smoothing parameter',x='Time to next eruption (min)',y='Density')
+ scale_color_identity(guide='legend')
)
,
看起来您发布的最后一个链接是在正确的轨道上,但是您必须欺骗python以克服R所做的一些非标准评估。我可以通过在颜色名称周围设置两组引号来使其工作:
(ggplot(faithful,aes(x='waiting'))
+ geom_line(aes(color="'red'"),adjust=0.5)
+ geom_line(aes(color="'blue'"),stat='density')
+ geom_line(aes(color="'green'"),adjust=2)
+ labs(title='Effect of ...',y='Density')
+ scale_color_identity(guide='legend',name='My color legend')
)
您可以像帖子一样制作自己的标签:
(ggplot(faithful,aes(x='waiting'))
+ geom_line(aes(color="'red'"),adjust=.5)
+ geom_line(aes(color="'blue'"),stat='density')
+ geom_line(aes(color="'green'"),adjust=2)
+labs(title='Effect of ...',y='Density')
+ scale_color_identity(guide='legend',name='My colors',breaks=['red','blue','green'],labels=['Label 1','Label 2','Label 3']))