0

I have a dataframe df with following values in its two columns:

Year Temperature
1750 8.719364
1751 7.976143
1752 5.779833
1753 8.388083
1754 8.469333
1755 8.355583
1756 8.849583
1757 9.022000
1758 6.743583
1759 7.985083
1760 7.185167

and so on for some 200 years with their corresponding temperatures.

I'm trying to plot a timeseries graph using plotly.

library(plotly)
g <- plot_ly(x=~df$Year, y=~df$Temperature, add_trace("scatter"), mode='lines')

And it's giving me

Error: $ operator is invalid for atomic vectors.

So, I tried assigning the columns into separate vectors as below, so as to avoid using $:

x <- avg.temp$Year
y <- avg.temp$Avg.Temp
g <- plot_ly(x=~x, y=~y, add_trace("scatter"), mode='lines')

but I still get the same error.

I'm new to R. And I was just trying to create a simple time series graph with Year and Temperature data. But I'm unable to figure out what the hell is going wrong with my code. Can someone please help me solve this error?

Also, what is add_trace("scatter") parameter? What does it do? I used it because I previously created a graph on the same data but it was not a single line. It was too thick, and it was giving me a warning telling me that a scatter trace would be appropriate here (or something like that..)

It would be awesome if someone can help me with this. Many thanks, guys.

MLavoie
  • 9,671
  • 41
  • 36
  • 56
LearneR
  • 2,351
  • 3
  • 26
  • 50

1 Answers1

0

This code creates your chart with no error:

g <- plot_ly(df, x = ~Year) %>%
  add_trace(type="scatter", y=~Temperature, name="Trace Temperature", mode="lines")

You call the add_trace after you've called plotly to avoid the error.

Another way of writing this that is closer to what you currently have is:

g <- plot_ly(x=~df$Year, y=~df$Temperature, mode="lines")
add_trace(g, type="scatter")

Unfortunately I can't help by explaining what a trace is. Hope that helped anyway!

Eugene Brown
  • 4,032
  • 6
  • 33
  • 47