PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 26, 2022

[FIXED] How make a gradient plot in R from a matrix data stored in a .csv file?

 August 26, 2022     csv, heatmap, matrix, r     No comments   

Issue

I have a xyz matrix stored in a .csv file that, for example, looks like the following:

   1  2  3  4
1  1  1 -1  1
2 -1  1  1  1
3  1 -1  1 -1
4  1  1 -1  1

where the rows are x, columns are y and entries are z. I could store this matrix in a dataframe.

I want to create a heatmap of this matrix, where the entries would just be two colors, depending on 1 or -1. The plot would look like the following for an 18 X 18 matrix (done by a colleague in matlab probably):

where, say, yellow is for 1 and blue for -1.

How can I do this in R?


Solution

Use geom_tile(). First you need to flatten your dataframe using melt from the package reshape2.

library(reshape2)
flat_df <- melt(t(df), value.name = "Value")
ggplot(data=flat_df,aes(y=y,x=x))+geom_tile(aes(fill=Value))+scale_y_reverse()

Output from above code



Answered By - Soccerama
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing