Colonel Beauvel
Colonel Beauvel

Reputation: 31161

Scatterplot with color gradient and additional point

After coming back to ggplot2 for some evolve scatterplot, I feel like I am lost: I have two datasets, df1 and df2 (this last being a single point).

>df1
    DATE        XOV        DAX
1  16479  2.1880142 -1.8203765
2  16482  2.7930760 -2.1501989
3  16483  2.8998516 -1.9903619
4  16484  1.8676874 -1.8704841
5  16485  1.5473606 -1.8007140
6  16486  1.3338094 -1.4620117
7  16489  0.7643395 -1.4512291
8  16490  0.4084208 -1.2044965
9  16491  0.2660533 -1.2577755
10 16492 -0.5169678 -0.9438099

>df2
   DATE      XOV       DAX
1 13514 1.620395 -1.927569

What I wanna obtain (1) is a scatterplot with df1, with point colored depending on the date, according to a gradient, and (2) add the single point in red on it with a bigger size.

I can obtain (1) with:

library(ggplot2)

ggplot() + 
geom_point(data=df1, aes(x=DAX, y=XOV, colour=DATE)) + 
theme(legend.position="none") + 
scale_colour_gradient(low="#A9C8F3", high="#0C2389")

Giving:

enter image description here

When I wanna add (2), I use:

library(ggplot2)

ggplot() + 
geom_point(data=df1, aes(x=DAX, y=XOV, colour=DATE)) + 
theme(legend.position="none") + scale_colour_gradient(low="#A9C8F3", high="#0C2389") + 
geom_point(data=df2, aes(x=DAX, y=XOV, color="red"))

But then get the error:

$ Discrete value supplied to continuous scale

I apologize if it's a duplicate, already looked for solutions but I did not get what was wrong, despite pulling each dataframe out of ggplot() ...

Upvotes: 1

Views: 3583

Answers (1)

Florian
Florian

Reputation: 25385

You should specify the colour argument outside of the aes:

ggplot() + 
  geom_point(data=df1, aes(x=DAX, y=XOV, colour=DATE)) + 
  theme(legend.position="none") + 
  scale_colour_gradient(low="#A9C8F3", high="#0C2389") +
  geom_point(data=df2, aes(x=DAX, y=XOV), colour="red",size=5)

enter image description here

Explanation for the behavior can be found here:

When specified inside aes, an aesthetic is mapped to the value of a variable in the data. Since there is a mapping between the data and the visible aesthetic, there is a legend which shows that mapping. Outside of an aes call, the aesthetic is just set to a specific value.

Upvotes: 1

Related Questions