0

I am looking for a solution where I can add a legend where you can see which color belongs to which asset. The code below gives me a nice figure but I need a legend too. Thanks in advance for any recommendation!

ggplot(data = Polkadot, aes(x=Date, y=Price.Last)) + geom_line(color="blue", size=1.5) + 
  geom_line(data = Cardano, aes(x=Date, y=Price.Last), color="blue4", size=1.5) +
  geom_line(data = Solana, aes(x=Date, y=Price.Last), color="cyan", size=1.5) +
  geom_line(data = Tezos, aes(x=Date, y=Price.Last), color="cyan4", size=1.5) +
  geom_line(data = Bitcoin, aes(x=Date, y=Price.Last), color="black", size=1.5) +
  geom_line(data = Basket, aes(x=Date, y=Price.Last), color="deepskyblue", size=1.5) +
  theme_bw()
``
marco
  • 1
  • 1
  • Welcome to SO! I think a better solution would be to `bind_rows` your datasets together before passing them to `ggplot`. You can add an indicator variable to define the source dataset. Use the indicator variable to define the `colour` aesthetic. This will result in more compact, more robust, code. And give you the legend you want automatically. – Limey Oct 29 '21 at 13:30
  • What Limey said! Putting the data into a single tidy dataframe will solve your problem. In addition, if you want some more practical help see here for instuctions on how to create a minimal reproducible example: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example?noredirect=1&lq=1 – Mojoesque Oct 29 '21 at 13:32
  • Thanks for your answers. I tried something similar but I think the problem is that the data sets have a different length... – marco Oct 29 '21 at 13:36

1 Answers1

0

To expand on my comment above...

library(tidyverse)

Polkadot %>% 
  bind_rows(Cardano, Solana, Tezos, Bitcoin, Basket, .id="Source") %>% 
  ggplot(aes(x=Date, y=Price.Last, colour=Source), size=1.5) + 
  geom_line() + 
  theme_bw()

Or, even better,

dsList <- list(Polkadot, Cardano, Solana, Tezos, Bitcoin, Basket)

dsList %>% 
  bind_rows(.id="Source") %>% 
  ggplot(aes(x=Date, y=Price.Last, colour=Source), size=1.5) + 
  geom_line() + 
  theme_bw()

So long as the datasets all have columns named Date and Price.Last, the fact that they have different row counts shouldn't matter.

You can use scale_colour_discrete() for fine control over the legend if you need to.

[Untested code, since you haven't given us any test data.]

Limey
  • 10,234
  • 2
  • 12
  • 32
  • So, with scale_colour_discrete() I can change the numers in the legends into other names? – marco Oct 29 '21 at 13:59
  • Yes. That's correct. You need the `labels` option for that. The online help isn't obvious. You need to read `discrete_scale()`, not `scale_colour_discrete()` for the details. or you could provide a *named* list to `bind_rows()` - something like `dsList <- list("Polkadot"=Polkadot, "Cardano'=Cardano, "Solana"=Solana, "Tezos"=Tezos, "Bitcoin"=Bitcoin, "Basket'=Basket)` and you should get the names for free. – Limey Oct 29 '21 at 14:04