Reputation: 119
I have the following dataframe:
Name <- c("Apple", "Banana", "Milk")
black <- c(1, 2, 3)
white <- c(10, 5, 999)
df <- data.frame(Name, black, white)
print (df)
That results in:
Name black white
1 Apple 1 10
2 Banana 2 5
3 Milk 3 999
I would like to transform it as follows:
X Y Z
1 black Apple 1
2 white Apple 10
3 black Banana 2
4 white Banana 5
5 black Milk 3
6 white Milk 999
Upvotes: 2
Views: 465
Reputation: 2157
library(tidyr)
long_df <- df |> pivot_longer(cols = c('black', 'white'), names_to = "X", values_to = "Z")
Slightly reorganised to keep the "Name" column name.
Name | X | Z |
---|---|---|
Apple | black | 1 |
Apple | white | 10 |
Banana | black | 2 |
Banana | white | 5 |
Milk | black | 3 |
Milk | white | 999 |
To produce a heatmap:
library(ggplot2)
long_df |> ggplot(aes(Name, X, fill = Z)) + geom_tile()
which is very skewed by the white milk value of 999.
Upvotes: 2
Reputation: 3
This is a short article where the author shows a nice way to generate heatmaps from dataframes, it will only take you two minutes.
https://datascientyst.com/display-pandas-dataframe-heatmap/
Upvotes: 0