Reputation: 83
I am trying to create a heatmap, but am confused as to how to. Here are the dataframes.
Ticker <- c("S&P 500","Dow Jones Index","AAPL","MSFT","FB","NFLX","GOOG","JPM","TSLA")
Values <- c(2, 1, 1, 1, 1, 1, 1, -1, -1)
ticker_matrix <- matrix(Ticker , nrow = 3, ncol = 3)
values_matrix <- matrix(Values, nrow = 3, ncol = 3)
How should i use ggplot2 to plot a heat map that looks like this?
the matrix plot is a 3x3 matrix whereby positive numbers are in green (the larger the number, the darker the green), and negative number in red, it will be even better.
Edit:
Thanks Camille for highlighting the broadness of the question, i shall narrow down the question further by making reference to d.b's answer.
d.b's answer is in the exact direction i am seeking. whereby the heatmap is shown in a 3x3 matrix based on the scale of underlying value in the background. (the purpose of this visualization is to show how positive or negative a particular stock's sentiment is)
Building on d.b's answer (whereby values are colored in discrete factors), i will post an alternative solution with continuous variables on the scale. Thanks all!
Upvotes: 1
Views: 879
Reputation: 83
continuous variable version (range from c(-1,2)) of d.b's answer:
d = data.frame(Ticker = as.vector(ticker_matrix),
Values = as.numeric(values_matrix),
X = as.vector(row(ticker_matrix)),
Y = as.vector(col(ticker_matrix)))
ggplot(data = d,
mapping = aes(x = factor(X),
y = factor(Y),
fill = Values,
label = Ticker)) +
geom_tile() +
geom_text() +
coord_equal() +
scale_fill_gradientn(colors = c("dark red", "red3", "white", "green3", "dark green"),
limits=c(-1, 2))
Upvotes: 1
Reputation: 32548
d = data.frame(Ticker = as.vector(ticker_matrix),
Values = as.vector(values_matrix),
X = as.vector(row(ticker_matrix)),
Y = as.vector(col(ticker_matrix)))
ggplot(data = d,
mapping = aes(x = factor(X),
y = factor(Y),
fill = factor(Values),
label = Ticker)) +
geom_tile(color = "white") +
geom_text() +
coord_equal()
If you want to remove axes and legends, check out the answers here.
Upvotes: 3