Conditional Coloring of Cells in Table

HTML Table Conditional Cell Color by Value Ranges

i think you can setup condition in js like this.





$(document).ready(function(){
$('#status_report tr td').each(function(){
if ($(this).text() == '-') {
$(this).css('background-color','RGBA(85,83,108,0.4)');
}else if ($(this).text() >=0 && $(this).text() <=15) {
$(this).css('background-color','RGBA(255,198,191,0.4)');
}else if ($(this).text() > 15 && $(this).text() <=20) {
$(this).css('background-color','RGBA(170,214,136,0.4)');
}else if ($(this).text() > 20 && $(this).text() <=25) {
$(this).css('background-color','RGBA(152,195,119,0.6)');
}else if ($(this).text() > 25 && $(this).text() <=30) {
$(this).css('background-color','RGBA(139,189,120,0.9)');
}else if ($(this).text() > 30) {
$(this).css('background-color','RGBA(94,167,88,0.9)');
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>DATA FRAME TABLE</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

</head>
<body>
<table id="status_report" border="1" class="table table-hover" data-vertable="ver1">
<tbody style="text-align: center;">
<tr>
<td>Name</td>
<td>Round 1</td>
<td>Round 2</td>
<td>Round 3</td>
<td>Round 4</td>
<td>Avg</td>
</tr>
<tr>
<td>Ben</td>
<td>19</td>
<td>24</td>
<td>22</td>
<td>27</td>
<td>23.0</td>
</tr>
<tr>
<td>Harry</td>
<td>21</td>
<td>19</td>
<td>15</td>
<td>19</td>
<td>18.5</td>
</tr>
<tr>
<td>Tom</td>
<td>10</td>
<td>22</td>
<td>18</td>
<td>21</td>
<td>17.8</td>
</tr>
<tr>
<td>Jack</td>
<td>18</td>
<td>19</td>
<td>16</td>
<td>17</td>
<td>17.5</td>
</tr>
<tr>
<td>Angus</td>
<td>13</td>
<td>-</td>
<td>21</td>
<td>19</td>
<td>17.2</td>
</tr>
</tbody>
</table>

</body>
</html>

React: Table column cells, conditional formatting with color scale

Here's an approach using a pickHex() function that returns a hue between 2 colors based on a weight (ratio).

I've sliced the original array down to 20 entries, to display a smaller table.

Scroll down, to find a link to a live Codesandbox demo.

import original_data from "./testData";

// Source: https://stackoverflow.com/questions/30143082/how-to-get-color-value-from-gradient-by-percentage-with-javascript#answer-30144587
function pickHex(color1, color2, weight) {
var w1 = weight;
var w2 = 1 - w1;
var rgb = [Math.round(color1[0] * w1 + color2[0] * w2),
Math.round(color1[1] * w1 + color2[1] * w2),
Math.round(color1[2] * w1 + color2[2] * w2)];
return rgb;
}

const green = [0,255,0];
const white = [255,255,255];
const red = [255,0,0];

// Green to White: 1 => 0
// console.log( pickHex(green,white, 1) );
// console.log( pickHex(green,white, 0.5) );
// console.log( pickHex(green,white, 0) );

// White top Red: 1 => 0
// console.log( pickHex(white,red, 1) );
// console.log( pickHex(white,red, 0.5) );
// console.log( pickHex(white,red, 0) );

export default function App() {
const data = original_data.slice(0,20);
return (
<div className="App">
<table>
<thead>
<tr>
<th>Market</th>
<th>Rank</th>
</tr>
</thead>
<tbody>
{data.map((item, index) => {
let backgroundColor;
const ratio = (index / (data.length / 2 ));
if ( ratio > 1 ){
console.log("We're in the middle...");
backgroundColor = pickHex(red,white,ratio-1);
} else {
backgroundColor = pickHex(white,green, ratio);
}
backgroundColor = `rgba(${backgroundColor.join(",")})`;
return (
<tr key={index}>
<td>{item.Market}</td>
<td style={{ backgroundColor }}>
{item.CombinedzScore}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}

Codesandbox Demo






<script>
const data = [
{
No: "16980",
Market: "Chicago-Naperville-Elgin, IL-IN-WI",
CombinedzScore: "131.71"
},
{
No: "31080",
Market: "Los Angeles-Long Beach-Anaheim, CA",
CombinedzScore: "128.07"
},
{
No: "35620",
Market: "New York-Newark-Jersey City, NY-NJ-PA",
CombinedzScore: "123.41"
},
{
No: "19100",
Market: "Dallas-Fort Worth-Arlington, TX",
CombinedzScore: "121.02"
},
{
No: "26420",
Market: "Houston-The Woodlands-Sugar Land, TX",
CombinedzScore: "120.88"
},
{
No: "12060",
Market: "Atlanta-Sandy Springs-Alpharetta, GA",
CombinedzScore: "120.59"
},
{
No: "19820",
Market: "Detroit-Warren-Dearborn, MI",
CombinedzScore: "119.17"
},
{
No: "16740",
Market: "Charlotte-Concord-Gastonia, NC-SC",
CombinedzScore: "112.22"
},
{
No: "24860",
Market: "Greenville-Anderson, SC",
CombinedzScore: "112.20"
},
{
No: "26900",
Market: "Indianapolis-Carmel-Anderson, IN",
CombinedzScore: "112.15"
}];
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
function pickHex(color1, color2, weight) {
var w1 = weight;
var w2 = 1 - w1;
var rgb = [Math.round(color1[0] * w1 + color2[0] * w2),
Math.round(color1[1] * w1 + color2[1] * w2),
Math.round(color1[2] * w1 + color2[2] * w2)];
return rgb;
}

const green = [0,255,0];
const white = [255,255,255];
const red = [255,0,0];

function App() {
return (
<div className="App">
<table>
<thead>
<tr>
<th>Market</th>
<th>Rank</th>
</tr>
</thead>
<tbody>
{data.map((item, index) => {
let backgroundColor;
const ratio = (index / (data.length / 2 ));
if ( ratio > 1 ){
backgroundColor = pickHex(red,white,ratio-1); } else {
backgroundColor = pickHex(white,green, ratio); }
backgroundColor = `rgba(${backgroundColor.join(",")})`;
return (
<tr key={index}>
<td>{item.Market}</td>
<td
style={{ backgroundColor }}
>
{item.CombinedzScore}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}


const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement );
</script>

Conditional styling of cells in a table based on a value range that differs per row (R)

The package tableHTML offers a lot of options for table styling, specially if you use some tricks with html code, for example one way to solve your issue would be the following:

based on the answer here Highlight Predefined Words in Shiny DT table [Not through Search Highlight]

You modify the data satisfying the conditions to include text formatting (or any other html formatting, font color, background color .....) and then pass it to tableHTML() with escape=FALSE

library(tableHTML)
library(dplyr)

a <- c('A', 'B', 'C', 'D', 'E')
b <- c(20, 25, 40, 55, 60)
c <- c(60, 30, 80, 50, 60)
min <- c(15, 20, 40, 55, 55)
max <- c(25, 30, 50, 65, 65)

df <- data.frame(a, b, c, min, max)

df %>%
mutate(b = ifelse(b < min | b > max, paste0('<font color="red">', b, '</font>'), b),
c = ifelse(c < min | c > max, paste0('<font color="red">', c, '</font>'), c)) %>%
`[`(1:3) %>%
tableHTML(escape = FALSE, rownames = FALSE,
widths = rep(50, 3), theme = 'scientific')

this would be the result

Sample Image

or maybe with two conditions and two colors:

df %>% 
mutate(b = ifelse(b < min ,
paste0('<span style="background-color:#ccccff">', b, '</span>'),
ifelse( b > max, paste0('<span style="background-color:#ff9999">', b, '</span>'),
b)),
c = ifelse(c < min ,
paste0('<span style="background-color:#ccccff">', c, '</span>'),
ifelse( c > max, paste0('<span style="background-color:#ff9999">', c, '</span>'),
c))) %>%
`[`(1:3) %>%
tableHTML(escape = FALSE, rownames = FALSE,
widths = rep(50, 3), theme = 'scientific')

You get :

Sample Image

The package offers a lot of formatting options and even conditional formatting (though not for this case), take a look here to see what else you can do with the package:

tableHTML Basics

conditional formatting

Update

There are many options to modify an unknown number of columns in a dataframe, I prefer working with the apply functions, like this for example:

Define a function to modify the columns:

(In this function col is any vector, min_col is the vector containing the lower bounds, and max_col is the vector containing the upper bounds)

add_format <- function(col, min_col, max_col){
if(!is.numeric(col)){
return(as.character(col))
}else{
new_col <- ifelse(col < min_col | col > max_col,
paste0('<font color="red">', col, '</font>'), col)
return(new_col)
}
}

and now apply this function on all columns in df, turn it to a data.frame and then the rest is the same

df %>% 
sapply(add_format, df$min, df$max) %>%
as.data.frame() %>%
`[`(1:3) %>%
tableHTML(escape = FALSE, rownames = FALSE,
widths = rep(50, 3), theme = 'scientific')

You could also check out the functions mutate_if and mutate_all, they would work as well with some playing around

Conditional table cell background color depending on value

To go with one cell, using your example that I copied for two others, changing the ID, could look something like this:





let listItem = {};
listItem.Title = 'subjectivegrading';
listItem.c3t9 = 5;

if (listItem.Title === "subjectivegrading") {
$("#SubjectiveDays").text(listItem.c3t9 + " Business Days");
$("#SubjectiveDays").addClass('red');
}

listItem.c3t9 = 10;
if (listItem.Title === "subjectivegrading") {
$("#SubjectiveDays2").text(listItem.c3t9 + " Business Days");
$("#SubjectiveDays2").addClass('yellow');
}

listItem.c3t9 = 15;
if (listItem.Title === "subjectivegrading") {
$("#SubjectiveDays3").text(listItem.c3t9 + " Business Days");
$("#SubjectiveDays3").addClass('green');
}
.red {
color: red;
}

.yellow {
color: yellow;
}

.green {
color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
<tr>
<td style="background-color:Black; color:White; text-align:center; font-weight:bold; border-
style:inset"><div id="SubjectiveDays"></div></td>
<td></td>
<td style="background-color:Black; color:White; text-align:center; font-weight:bold; border-
style:inset"><div id="SubjectiveDays2"></div></td>
<td></td>
<td style="background-color:Black; color:White; text-align:center; font-weight:bold; border-
style:inset"><div id="SubjectiveDays3"></div></td>
<td></td>
</tr>
</table>


Related Topics



Leave a reply



Submit