【发布时间】:2020-09-29 12:36:48
【问题描述】:
当曲线因要绘制的行的选择而不同时,有几个人询问如何在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'), 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)".
关于如何添加图例的任何建议?谢谢。
【问题讨论】: