ggplot2中两个离散尺度的图例

时间:2016-05-12 07:27:56

标签: r ggplot2 axis

我有想要沿两个维度绘制的数据:VK(离散)和relPrec(连续)

此外,我有两个维度的属性:

type <- c("relPrecAir", "relPrecInv", "relPrectotal")
p <- c(0.9, 0.95, 0.99)

我想用type表示形状,用p表示颜色。我设法使用以下代码执行此操作:

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")

p显示了一个图例。但我无法使用形状值为type绘制第二个图例。我该如何添加它?

My try, legend for shapes is missing

2 个答案:

答案 0 :(得分:1)

我们可以通过为参数relPrecTotalrelPrecAirrelPrecInv添加新的分组来处理它,然后使用ggplot绘制它。

编辑覆盖颜色传奇中的形状

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)))

edit

答案 1 :(得分:0)

您可以melt您的data.frame以避免ggplot命令中的多个步骤,并创建一个新的变量(此处ptShape),您将在{{1}内映射一个aes来电:

geom_point

enter image description here