Search code examples
rtime-seriesheatmapquantmod

Hello, I have a problem when I try to creating heatmap. It just won't show


I try to create heatmap in R using ggplot where I want the X-axis to be the date and Y-axis to be the return. I exported a stock data using quantmod and I calculated the daily returns. This is my code:

library(quantmod)
library(zoo)
library(ggplot2)
library(dplyr)

test1=getSymbols("BTC-USD",auto.assign=F)
test2=dailyReturn(test1)
test2=test2%>%fortify.zoo()%>%mutate(dr=daily.returns*100)
fig1=ggplot(data=test2,aes(x=Index,y=dr,fill=dr))+geom_tile()

When I run the code above, it returned an empty plot like this

enter image description here

Now, what I'm expecting is a plot like this.

enter image description here

Where the X-axis is the date and the Y-axis is the returns. The Y-axis should be from -1.5 to 1.5. Is there any way to make heatmap with only 2 values (the date and the returns)?


Solution

  • I think you are far away from your goal: Here is a starting point: Note these are only data for 10 days and you have over 3000 days!

    library(quantmod)
    library(zoo)
    library(ggplot2)
    library(dplyr)
    
    test1=getSymbols("BTC-USD",auto.assign=F)
    test2=dailyReturn(test1)
    test3 <- test2%>%
        fortify.zoo()%>%
        mutate(dr=daily.returns*100)
    
    
    test4 <- test3 %>% 
      slice(1:10) %>% 
      mutate(new = rep(1, 10))
    
      
      # Create plot
      ggplot(test4, aes(Index, new, fill = dr)) +
        geom_tile(color = "black", height = 1.6, width = 0.8) +
        scale_fill_gradient(low = "white", high = "red") +
        theme_void() +
        ylim(-2,2)+
        theme(axis.text.x = element_text(angle = 45, hjust = 1))+
        geom_text(aes(label = round(dr,1)), size = 3, color = "black")+
        scale_x_continuous(breaks = test4$Index, labels = format(test4$Index, "%Y-%m-%d"), 
                           expand = c(0.05, 0)) +
        theme(legend.position = "none",
              axis.ticks.x = element_blank(),
              axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1),
              plot.margin = unit(c(8,0.5,1,1), "cm")) +
        ggtitle("dr by date")
    

    enter image description here