First, you need to format your data frame from wide format to long format. The following is an example using tidyverse to format the data frame.

library(tidyverse)

dt2 <- dt %>%
  rownames_to_column() %>%
  gather(colname, value, -rowname)
head(dt2)
#          rowname colname        value
# 1        tension tension           NA
# 2        cluster tension 1.943113e+08
# 3 migraineNoAura tension 8.462798e+00
# 4   migraineAura tension 2.833333e+00
# 5        tension cluster 1.500000e+00
# 6        cluster cluster           NA

Now we are ready to use the ggplot2 to plot the heatmap using geom_tile.

ggplot(dt2, aes(x = rowname, y = colname, fill = value)) +
  geom_tile()

Answer from www on Stack Overflow
🌐
R Graph Gallery
r-graph-gallery.com › 215-the-heatmap-function.html
Building heatmap with R – the R Graph Gallery
How to do it: below is the most basic heatmap you can build in base R, using the heatmap() function with no parameters. Note that it takes as input a matrix.
Discussions

How to make a “heatmap” from a data frame where two columns represent the x and y axis coordinates and a third represents the value to be mapped to the color?
The key is to pivot your dataframe. Example: import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # Prep to generate dataframe like question np.random.seed(42) nX = 20 # number of X variables nY = 40 # number of Y variables Z = np.random.randn(nX, nY).flatten() X = np.repeat(np.arange(nX), nY) Y = np.tile(np.arange(nY), nX) df = pd.DataFrame({ # Just to drive the point home that these coordinates # are not index numbers or column names 'X': "FOO" + pd.Series(X).astype(str).str.zfill(2), 'Y': "BAR" + pd.Series(Y).astype(str).str.zfill(2), 'Z': Z }) # Pivot the dataframe df_pivot = df.pivot(index='X', columns='Y', values='Z') print(df_pivot) ax = sns.heatmap(df_pivot, cmap="YlGnBu") ax.set_title("Heatmap of Z values") plt.show() More on reddit.com
🌐 r/learnpython
2
5
May 23, 2023
R: Use dataframe for heatmap - Stack Overflow
Now I would like to show the values of col1 to col5 in the columns of the heatmap and every row in the dataframe is a row in the heatmap. More on stackoverflow.com
🌐 stackoverflow.com
dataframe - How to create a heatmap in R with data frames - Stack Overflow
I would like to generate a heatmap of some data so that the density can be seen indirectly. But the problem is that the data had to be parsed from an xml file and were saved in a data frame. I know... More on stackoverflow.com
🌐 stackoverflow.com
May 8, 2016
making matrix from dataframe to make heatmap in R - Stack Overflow
I want to make heatmap in R but I could not change the dataframe to appropriate matrix form. I have a dataframe with three columns (protein,value and treatments) in columns proteins and treatments ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Jcoliver
jcoliver.github.io › learn-r › 006-heatmaps.html
Heatmaps in R – learn-r
mine_heatmap <- ggplot(data = mine_long, mapping = aes(x = Sample.name, y = Class, fill = Abundance)) + geom_tile() + xlab(label = "Sample") + facet_grid(~ Depth, scales = "free_x", space = "free_x") mine_heatmap · Passing "free_x" to the scales argument instructs R to allow different x-axis for each of our sub-plots. In this case, the default is for each site to appear in each sub-plot. Specifying scales = "free_x" removes any site from a sub-plot where there is no corresponding data.
🌐
GeeksforGeeks
geeksforgeeks.org › r language › create-heatmap-in-r-using-ggplot2
Create Heatmap in R Using ggplot2 - GeeksforGeeks
June 8, 2023 - Melting in R programming is done to organize the data. It is performed using melt() function which takes dataset and column values that have to be kept constant. Using melt(), dataframe is converted into a long format and stretches the data frame.
🌐
Rdrr.io
rdrr.io › github › richysix › biovisr › man › df_heatmap.html
df_heatmap: Create heatmap plot for a data.frame in richysix/biovisr: Biological Visualisation Functions
June 12, 2025 - rdrr.io Find an R package R language docs Run R in your browser ... Browse all... ... df_heatmap( plot_df, x, y, fill, fill_palette = "plasma", colour = NULL, size = NULL, xaxis_labels = TRUE, yaxis_labels = TRUE, na.translate = TRUE, ...
🌐
RPubs
rpubs.com › geock › hvr
RPubs - Lesson 9 Heatmap Visualisation with R
Sign in Register · Lesson 9 Heatmap Visualisation with R · by Kai Cao · Last updated almost 6 years ago · Hide Comments (–) Share Hide Toolbars ·
🌐
Reddit
reddit.com › r/learnpython › how to make a “heatmap” from a data frame where two columns represent the x and y axis coordinates and a third represents the value to be mapped to the color?
r/learnpython on Reddit: How to make a “heatmap” from a data frame where two columns represent the x and y axis coordinates and a third represents the value to be mapped to the color?
May 23, 2023 -

I have been really struggling with how to do this. I’ve tried the following functions, but haven’t had success for the following reasons:

Heatmap - uses the index numbers and column names as opposed to the values in certain columns

Hexbin/2D histogram - my problem has nothing to to with frequency or “binning”, all the values are explicitly associated with a set of coordinates

Imshow - I can generate an image similar to what I want if I put the value column in a 2D array, but then when I graph, the axis values are based on the indices of the array and I lose all association between the values and the actual original coordinates

My friend showed me how to do it in R using ggplot/geom_tile, but I haven’t been able to find anything similar in Python

Find elsewhere
🌐
ProgrammingR
programmingr.com › home › animation and graphics in r
How To Make a Heatmap in R (With Examples) - ProgrammingR
November 28, 2021 - Ironically, it is more complicated than those using real-world data from existing R data sets. However, most of this is due to the need to set up the data frame, and the row and column labels. Since this is what you will need to do when you are working with your own data as opposed to data sets provided by R packages, it is part of the basic process. # how to make a heatmap in R ds = data.frame(rnorm(5, 50, 20),rnorm(5, 50, 20),rnorm(5, 50, 20),rnorm(5, 50, 20)) rn = c("Arm","Leg","Chest","Gut","Head") cn = c("Ann","Bob","Tom","Joy") x = data.matrix(ds, rownames.force = FALSE) heatmap(x, labRow=rn, labCol=cn, main = "Test Heat Map")
🌐
Medium
vivdas.medium.com › create-heatmap-in-r-using-ggplot2-d4c02dccec28
Create Heatmaps in R Using ggplot2 | by Vivekananda Das | Medium
October 23, 2025 - Let’s have a quick look at the g2 dataframe. We want to remove the Xs from the beginning of the column names. #Remove “X” from the beginning of column names for ( col in 1:ncol(g2)){ colnames(g2)[col] <- sub(“X”, “”, colnames(g2)[col]) } Okay, now g2 becomes this: Although the data presented above in the matrix format is useful, keeping track of all the numbers and identifying patterns is difficult. This is where a heatmap comes into play and makes visualization much easier.
🌐
Uqlibrary
uqlibrary.github.io › technology-training › R › heatmaps › heatmaps_intermediate.html
R data visualisation: heatmaps – UQ Library Technology Training
stats::heatmap(): scale (row) -> cluster -> colour gplots::heatmap.2(): cluster -> scale (none) -> colour pheatmap::pheatmap(): scale (none) -> cluster -> colour · If you want to stick to the ggplot2 package for all your data visualisation, there is a way to create a simple heatmap (without clustering). So far, we have seen methods that make use of data matrices; however, ggplot2 deals with dataframes that contain “tidy data”.
🌐
Datanovia
datanovia.com › learn › machine learning › clustering heatmaps in r: heatmap, pheatmap & more
Clustering Heatmaps in R: heatmap, pheatmap & More – Datanovia
Base heatmap() ships with R and needs no install, but its styling is plain and annotating it is fiddly (you build color side-bars by hand). pheatmap() (“pretty heatmap”) gives cleaner defaults, draws nicer dendrograms, cuts the tree into groups with cutree_rows, and annotates rows and columns directly from a data frame with annotation_row / annotation_col.
🌐
GeeksforGeeks
geeksforgeeks.org › r language › create-heatmap-in-r
Create Heatmap in R - GeeksforGeeks
July 23, 2025 - heatmap() function comes with the default installation of the Base R. One can use the default heatmap() also if he does not want to install any extra package. We can plot heatmap of the dataset using this heatmap function from the R.
🌐
Stack Overflow
stackoverflow.com › questions › 27128852 › how-to-create-a-heatmap-in-r-with-data-frames
dataframe - How to create a heatmap in R with data frames - Stack Overflow
May 8, 2016 - There is a new package out called heatmap.plus that may help you. It allows for a wider set of input formats than the original heatmap package. Documentation is here: http://cran.r-project.org/web/packages/heatmap.plus/heatmap.plus.pdf
Top answer
1 of 2
2

You may do either of these 2

df <- read.table(header = T, text = "protein           value    treatment
EPN1              0.986    treat1
LAMB1             0.881    treat2
PKP4              0.827    treat2     
PKP2              0.739    treat3     
BAIAP2            0.519    treat2     
UTRN              0.502    treat4     
REPS2             0.481    treat2     
PKP4              0.365    treat1      
LAMC1            -0.529    treat2     
PPIB              2.86     treat4 ")

library(tidyverse)
df %>% ggplot(aes(x= treatment, y = protein, fill = value)) +
  geom_tile()


OR

library(echarts4r)

df |> 
  e_charts(protein) |> 
  e_heatmap(treatment, value) |> 
  e_visual_map(value)

2 of 2
1

Here is some example data.

dat <- data.frame(
    protein=replicate(100, paste(sample(LETTERS, 4), collapse="")),
    value=rnorm(100),
    treatment=paste0("treat", sample(1:4, 100, replace=TRUE)),
    stringsAsFactors=FALSE
)

Using ggplot2 you could do

library(ggplot2)
plt <- ggplot(dat, aes(treatment, protein, fill=value)) + geom_tile()

More options you can find here: https://www.r-graph-gallery.com/79-levelplot-with-ggplot2.html

However, I don't know how to deal with a lot of proteins to plot (as you mentioned). Do you need to see the names of the proteins?

EDIT: one possibility for 1000 proteins would be to make the chart really long, like so:

ggsave(
    "long.pdf", plot=plt, device="pdf", 
    width=21, height=150, units="cm", limitsize=FALSE
)

This creates a PDF in the current folder. Using the zoom function of your PDF-Viewer, you can then navigate to the rows of interest.

EDIT 2: For more complex charts I (still) rely on base R. But maybe there are some ggplot-Style packages I am not aware of. A base R solution requires to convert the data into a matrix first. One approach would be to use a sparse matrix like this:

dim_x <- unique(dat$protein)
dim_y <- unique(dat$treatment)
map_x <- setNames(seq_along(dim_x), dim_x)
map_y <- setNames(seq_along(dim_y), dim_y)

library(Matrix)
mat <- sparseMatrix(
    i=map_x[dat$protein], j=map_y[dat$treatment], x=dat$value, 
    dims=c(length(dim_x), length(dim_y)), dimnames=list(dim_x, dim_y)
)

Then you can use the base R heatmap function,

heatmap(as.matrix(mat))

or some more customizeable function like

library(pheatmap)
pheatmap(mat)

which both show dendograms.

🌐
RPubs
rpubs.com › lumumba99 › 1026665
RPubs - Tutorial: Creating Heatmap in Rstudio
Sign in Register · Tutorial: Creating Heatmap in Rstudio · by Victor Lumumba · Last updated over 3 years ago · Hide Comments (–) Share Hide Toolbars ·
🌐
YouTube
youtube.com › biostatsquid
Step-by-step heatmap tutorial in R with pheatmap() - YouTube
In this tutorial, we will learn how to create and customise a heatmap to visualise our differential gene expression analysis results. We will use the R packa...
Published: May 20, 2023
Views: 10K
Top answer
1 of 1
2

Data:

df <- read.table(text = "allPoints.xLocs allPoints.yLocs allPoints.patchStatus
1       67.30330212       87.857495                     0
                 2       69.60800088       77.959314                     0
                 3       74.63313295       93.059260                     0
                 4       92.59099136       77.732215                     1
                 5       18.05288289       61.200910                     1
                 6       55.83499856       50.993785                     0
                 7       12.15664148       58.220179                     1
                 8       41.50413859       92.529054                     0
                 9       83.08209025       24.567501                     0
                 10      53.50615149       46.339927                     0", header = TRUE, stringsAsFactors = FALSE)

listofdfs <- list(df, df)

Code:

library('data.table')
listofdfs <- lapply(seq_len(length(listofdfs)), function(i){
  x <- listofdfs[[i]]
  # assign id and combine x and y coordinates
  setDT(x)[, `:=` ( id = i, coords = paste0(allPoints.xLocs, ",", allPoints.yLocs)) ]
} )

# combine list into a data table.
df2 <- rbindlist(l = listofdfs)

Plot

library('ggplot2')
ggplot( data = df2, mapping = aes( x = coords, y = factor(id) ) ) +  # draw heatmap
  geom_tile( aes( fill = factor(allPoints.patchStatus) ),  colour = "white") +
  coord_flip() + 
  scale_fill_discrete(name = "Patch Status") +
  labs( x = "Coordinates", y = "Data Frame Number")

Graph:

You can loop through the list of data frames and create heatmap for each dataframe. Below, I am showing how to get a heatmap for one data frame.

Plot-2

ggplot( data = df, mapping = aes( x = factor(allPoints.xLocs), y = factor(allPoints.yLocs) ) ) + 
  geom_tile( aes( fill = factor(allPoints.patchStatus) ),  colour = "white") +
  scale_fill_discrete(name = "Patch Status") +
  labs( x = "X-Coordinate", y = "Y-Coordinate") +
  theme_bw() + 
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

Graph-2

Plot-3 df data is used from above - see Data section at the top.

library('data.table')
listofdfs <- list(df, df)
df2 <- rbindlist(l = listofdfs)
df2 <- df2[, .(sum_patch = sum(allPoints.patchStatus)), by = .(allPoints.xLocs, allPoints.yLocs)]

library('ggplot2')
ggplot( data = df2, mapping = aes( x = factor(allPoints.xLocs), y = factor(allPoints.yLocs) ) ) + 
  geom_tile( aes( fill = sum_patch ),  colour = "white") +
  labs( x = "X-Coordinate", y = "Y-Coordinate") +
  theme_bw() + 
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

Graph-3:

🌐
Bioinformatics for Beginners
bioinformatics.ccr.cancer.gov › docs › data-visualization-with-r › Lesson5_intro_to_ggplot
Lesson5: Visualizing clusters with heatmap and dendrogram - Data Visualization with R
A common method for scaling is to use the z score (see z score formula), which tells us how many standard deviations away from the mean is a given value in our data. This is the scaling method for pheatmap. z score=(individual value - mean) \ (standard deviation) Below, we will use the mtcars data to look at how scaling influences a heatmap. Because mtcars is built into R, we can use the data command to load it and we will save this as an object named cars.