ggplot添加自定义样本

时间:2017-07-26 15:05:50

标签: r ggplot2 legend point

我使用以下代码(仅限相关部分)生成我的图表

p <- ggplot(avg.dice, aes(x=type, y=average)) +
    theme_bw() +
    geom_point() +
    geom_point(aes(x=type, y=cc.average), col="red", shape = 8) +
    geom_errorbar(aes(ymin=ci.lower, ymax=ci.upper))+
    theme(plot.margin=unit(c(2,2,2,3),"lines"))

enter image description here

如何制作一个图例,表明红色星号是“test1”而黑色实心点是“test2”?这两个点都是使用不同颜色和形状的geom_point生成的。

我的数据点如下:

median.dice
      type median ci.lower ci.upper cc.median
1      e70 0.6250    0.550    0.725     0.575
2      e89 0.5500    0.450    0.650     0.525
3      f10 0.6500    0.550    0.725     0.525
4      f15 0.4500    0.375    0.525     0.325
5      f20 0.6000    0.525    0.675     0.600
6      f22 0.4500    0.400    0.525     0.350
7      f48 0.3000    0.200    0.500     0.125
8      f80 0.6500    0.550    0.750     0.350
9     i3i8 0.5500    0.500    0.650     0.400
10      m5 0.6250    0.550    0.725     0.575
11 series6 0.5500    0.500    0.675     0.350
12 series7 0.5375    0.450    0.625     0.425
13      x3 0.6250    0.550    0.725     0.750
14   z4e85 0.5750    0.500    0.675     0.625

1 个答案:

答案 0 :(得分:2)

使用scale_shape_manualscale_colour_manual同时在shape来电中指定colouraes geom_point也应该有效。

ggplot(median.dice, aes(x=type, y=median)) +
    theme_bw() +
    geom_point(aes(colour = 'test2', shape = 'test2')) +
    geom_point(aes(x = type, y = cc.median, colour = 'test1', shape = 'test1')) +
    geom_errorbar(aes(ymin=ci.lower, ymax=ci.upper))+
    theme(plot.margin=unit(c(2,2,2,3),"lines"))+
    scale_shape_manual(values = c('test1' = 8, 'test2' = 16), name = 'Test')+
    scale_colour_manual(values = c('test1' = 'red', 'test2' = 'black'), name = 'Test')

enter image description here

数据

median.dice <- structure(list(type = c("e70", "e89", "f10", "f15", "f20", "f22", 
"f48", "f80", "i3i8", "m5", "series6", "series7", "x3", "z4e85"
), median = c(0.625, 0.55, 0.65, 0.45, 0.6, 0.45, 0.3, 0.65, 
0.55, 0.625, 0.55, 0.5375, 0.625, 0.575), ci.lower = c(0.55, 
0.45, 0.55, 0.375, 0.525, 0.4, 0.2, 0.55, 0.5, 0.55, 0.5, 0.45, 
0.55, 0.5), ci.upper = c(0.725, 0.65, 0.725, 0.525, 0.675, 0.525, 
0.5, 0.75, 0.65, 0.725, 0.675, 0.625, 0.725, 0.675), cc.median = c(0.575, 
0.525, 0.525, 0.325, 0.6, 0.35, 0.125, 0.35, 0.4, 0.575, 0.35, 
0.425, 0.75, 0.625)), .Names = c("type", "median", "ci.lower", 
"ci.upper", "cc.median"), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", 
"14"))