Customize legend in ggplot

2019-07-04 02:31发布

问题:

I need help customizing a graph with ggplot2. Below is the code I am using and the resulting graph:

> p=ggplot(a2,aes(x=grid,y=median))+geom_line(size=1.3)+
    geom_line(aes(x=grid,y=lower,linetype=2,colour='red'),size=1.3)+
    geom_line(aes(x=grid,y=upper,linetype=2,colour='red'),size=1.3)+
    geom_line(aes(x=trueX,y=trueY,linetype=1,colour='blue'),size=.8)+
    geom_line(aes(x=grid,y=xDens,linetype=1),size=.5)+
    geom_point(data=a1,aes(x=X,y=Y),size=1)

First, the colors red and blue seem off from what they should be. Second, I would like to customize the legend with four entries:

  1. Fit (black line)
  2. Conf Int (red dashed line)
  3. True Curve (blue line)
  4. X Density (small black line)

I have been playing with it for awhile but can't figure it out. Would appreciate suggestions.

I might need to rearrange my data to get what I want, here is a preview of what I have now (ignoring the data set a1 with the points):

> head(a2[,c(1,2,4,5,6,7,8)])
     lower    upper   median      grid   trueX     trueY    xDens
1 26.65933 28.83431 27.54782 -4.845770 -3.998449 27.73697 0.02803692
2 26.65933 28.77224 27.54284 -4.826273 -3.967264 27.71877 0.02902979
3 26.65933 28.77224 27.54284 -4.806776 -3.910030 27.68470 0.02953585
4 26.65933 28.77224 27.54284 -4.787279 -3.898646 27.67782 0.03056721
5 26.65933 28.77224 27.54284 -4.767782 -3.891712 27.67361 0.03162419
6 26.65933 28.77224 27.54284 -4.748285 -3.890767 27.67304 0.03270666

回答1:

probably this is near from what you want:

sample data:

> d
     lower    upper   median      grid     trueX    trueY      xDens
1 26.65933 28.83431 27.54782 -4.845770 -3.998449 27.73697 0.02803692
2 26.65933 28.77224 27.54284 -4.826273 -3.967264 27.71877 0.02902979
3 26.65933 28.77224 27.54284 -4.806776 -3.910030 27.68470 0.02953585
4 26.65933 28.77224 27.54284 -4.787279 -3.898646 27.67782 0.03056721
5 26.65933 28.77224 27.54284 -4.767782 -3.891712 27.67361 0.03162419
6 26.65933 28.77224 27.54284 -4.748285 -3.890767 27.67304 0.03270666

code:

d2 <- melt(subset(d, select = -c(trueX)), id = "grid")
ggplot(d2, aes(grid, value, colour = variable, linetype = variable, size = variable)) +
  geom_line() +
  scale_colour_manual("", values = c("red", "red", "black", "blue", "black"), breaks = levels(d2$variable)) +
  scale_linetype_manual("", values = c(2, 2, 1, 1, 1), breaks = levels(d2$variable)) +
  scale_size_manual("", values = c(0.5, 0.5, 0.5, 0.5, 0.25), breaks = levels(d2$variable))

output:



标签: r ggplot2