Brian Smith
Brian Smith

Reputation: 1353

Custom legend with ggplot

Let say I have below plot using ggplot2 package

library(ggplot2)

Data = data.frame('Date' = as.Date("2028-01-01") + 1:7,
                    'y' = c(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0),
                    'yLow' = c(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0) - 2.2,
                    'yUp' = c(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0) + 2.2,
                    'Pt1' = c(-1, 1.0, NA, NA, 4.0, 5.0, NA) + 3.2,
                    'Pt2' = c(NA, 1.0, 2, NA, 4.0, 5.0, NA) + 4.2)
Data

ggplot(Data, aes(x = Date, y = y)) +
        geom_line(size = 1, alpha = 0.8) +
        geom_ribbon(aes(ymin = yLow, ymax = yUp), fill = "blue", alpha = 0.2) +
        geom_point(aes(x = Date, y = Pt1),  color = "blue", shape = 23) 

Now I want to make a custom legend in this plot. This legend will only show the information for the area between yLow and yUp as a rectangle filled with blue color (with alpha 0.2), and information for y as line and information for Pt1 as a point with shape 23

Here is an example, how I want to have the legend -

enter image description here

I also want to place the legend in the plot area.

Is there any way to achieve this?

Any pointer will be highly appreciated.

Thanks,

Edited with the answer from @bird

The answer works as long as I have only one variable to be plotted as point i.e. Pt1. But if I add another similar variable Pt2, I get error :

ggplot(Data, aes(x = Date, y = y)) +
        geom_line(size = 1, alpha = 0.8, aes(linetype = "My line")) +
        geom_ribbon(aes(ymin = yLow, ymax = yUp, fill = "My area"), alpha = 0.2) +
        geom_point(aes(x = Date, y = Pt1, col = "My point"), shape = 23) +
        scale_color_manual("",values = c("My point"="blue")) +
        scale_fill_manual("",values = c("My area"="blue")) +
        scale_linetype_manual("", values = c("My line"="solid")) +

        geom_point(aes(x = Date, y = Pt2, col = "My point2"), shape = 23) +
        scale_color_manual("",values = c("My point2"="red")) 

This gives error as

Scale for 'colour' is already present. Adding another scale for 'colour',
which will replace the existing scale.
Error: Insufficient values in manual scale. 2 needed but only 1 provided.

I have few such variables to be plotted as point. Is there any way to solve this problem?

Upvotes: 1

Views: 642

Answers (1)

bird
bird

Reputation: 3294

One solution would be:

ggplot(Data, aes(x = Date, y = y)) +
        geom_line(size = 1, alpha = 0.8, aes(linetype = "My line")) +
        geom_ribbon(aes(ymin = yLow, ymax = yUp, fill = "My area"), alpha = 0.2) +
        geom_point(aes(x = Date, y = Pt1, col = "My point"), shape = 23) +
        scale_color_manual("",values = c("My point"="blue")) +
        scale_fill_manual("",values = c("My area"="blue")) +
        scale_linetype_manual("", values = c("My line"="solid"))

enter image description here

Upvotes: 1

Related Questions