[英]Legends for two discrete scales in ggplot2
I have data which I want to plot along two dimensions: VK (discrete) and relPrec (continous) 我有要沿两个维度绘制的数据:VK(离散)和relPrec(连续)
Additionally, I have attributes along two dimensions: 此外,我在两个方面都有属性:
type <- c("relPrecAir", "relPrecInv", "relPrectotal")
p <- c(0.9, 0.95, 0.99)
I want to represent type
with shapes and p
with colors. 我想用形状表示type
,用颜色表示p
。 I manage to do so with the following code: 我设法做到以下代码:
precisionTable <- structure(list(relPrecTotal = c(0, 0, 0, 0.0070300473755567, 0.00842647198124317, 0.0112374693913644), relPrecAir = c(0, 0, 0, 0.00700370093237813, 0.00839489217055491, 0.011195354831821), relPrecInv = c(0, 0, 0, 0.0108917034179065, 0.0130551941937278, 0.0174102928813975), p = c(0.9, 0.95, 0.99, 0.9, 0.95, 0.99), VK = c(0, 0, 0, 1.15, 1.15, 1.15), case = c("demandStochastic", "demandStochastic", "demandStochastic", "demandStochastic", "demandStochastic", "demandStochastic")), .Names = c("relPrecTotal", "relPrecAir", "relPrecInv", "p", "VK", "case"), row.names = c(NA, -6L), class = "data.frame")
ggplot(precisionTable, aes(VK, relPrecTotal, color=as.factor(p))) + geom_line() + geom_point(shape=19) +
geom_line(aes(VK,relPrecAir, color=as.factor(p))) + geom_point(aes(VK,relPrecAir), shape=17) +
geom_line(aes(VK,relPrecInv, color=as.factor(p))) + geom_point(aes(VK,relPrecInv), shape=15) +
scale_color_discrete(name="p")
One legend is shown for p
. 为p
显示了一个图例。 But I am not able to draw a second legend for type
with the shape values. 但我不能够得出一个第二个传说的type
与形状值。 How can I add it ? 如何添加呢?
We can work on it by adding new grouping for the parameters relPrecTotal
, relPrecAir
and relPrecInv
, then proceed to plot it using ggplot. 我们可以通过为参数relPrecTotal
, relPrecAir
和relPrecInv
添加新的分组来进行relPrecInv
,然后使用ggplot对其进行绘制。
EDIT Overriding the shape in color's legend 编辑覆盖颜色图例中的形状
library(reshape2)
precisionTable2 <- melt(precisionTable, measure.vars = c("relPrecTotal", "relPrecAir", "relPrecInv"))
ggplot(precisionTable2, aes(VK, value)) +
geom_line(aes(color=as.factor(p), shape=as.factor(variable))) +
geom_point(aes(color=as.factor(p),shape=as.factor(variable))) +
scale_color_discrete(name='p') +
scale_shape_discrete(name='relPrec') +
guides(color=guide_legend(override.aes = list(shape=NA)))
You could melt
your data.frame to avoid the multiple steps in your ggplot
command, and create a new variable (here ptShape
) that you would map within the aes
of a single geom_point
call: 您可以melt
data.frame以避免ggplot
命令中的多个步骤,并创建一个新变量(此处为ptShape
),您可以在单个geom_point
调用的aes
中映射该geom_point
:
library(reshape2)
pmelt = melt(precisionTable, id.vars=c('VK', 'p', 'case'))
pmelt$ptShape = rep(c(19,17,15), each=6)
ggplot(pmelt, aes(x=VK, y=value)) +
geom_line(aes(colour=as.factor(p), shape=as.factor(ptShape))) +
geom_point(aes(colour=as.factor(p), shape=as.factor(ptShape)), size=5)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.