yuhengd yuhengd - 1 year ago 39
R Question

ggplot add customized sample

I am using the following code (related part only) to generate my graph

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

How can I make a legend showing that the red star is for "test1" and the black solid dot is for "test2"? Both points are generated using geom_point with different color and shape.

My data points look like this:

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

Answer Source

Using scale_shape_manual and scale_colour_manual while also specifying shape and colour within aes in the geom_point calls should work.

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

data

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"))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download