Font Coloring Using xlsx Package in R - r

I am writing an R function to save out pre-formatted data frames. Part of the format template calls for changing the column heading font color. The cell styling returns the correct alignment and bolding, but the text is still black.
The below is a bare version to demonstrate my font coloring problem (just change the file_path variable to a location that exists).
library(xlsx)
file_path <- "C:/Users/.../Desktop/tst.xlsx"
wb <- createWorkbook()
headerStyle <- CellStyle(wb,
font = Font(wb, isBold=TRUE, color = "#ffffff"),
fill = Fill(foregroundColor = "#2db6e8",
pattern = "SOLID_FOREGROUND"),
alignment = Alignment(wrapText = TRUE,
horizontal = "ALIGN_CENTER",
vertical = "VERTICAL_CENTER")
)
x <- mtcars
sheet <- createSheet(wb, "test")
cellBlock <- CellBlock(sheet,
startRow = 1,
startCol = 1,
noRows = nrow(x) + 1,
noColumns = ncol(x) + 1,
create = TRUE)
CB.setRowData(cellBlock = cellBlock,
x = colnames(x),
rowIndex = 1,
colOffset = 1,
rowStyle = headerStyle +
Border(pen = "BORDER_MEDIUM", color = "black",
position = "BOTTOM"))
saveWorkbook(wb, file_path)

I was able to get white text using the color index from the INDEXED_COLORS_ constant which is 9 for white. For your example code it would read:
headerStyle <- CellStyle(wb,
font = Font(wb, isBold=TRUE, color = "9"),
fill = Fill(foregroundColor = "#2db6e8",
pattern = "SOLID_FOREGROUND"),
alignment = Alignment(wrapText = TRUE,
horizontal = "ALIGN_CENTER",
vertical = "VERTICAL_CENTER")
)

It seems to relate uniquely to white text. Try using different colors:
headerStyle <- CellStyle(wb,
font = Font(wb, isBold=TRUE, color = "grey"),
fill = Fill(foregroundColor = "#2db6e8",
pattern = "SOLID_FOREGROUND"),
alignment = Alignment(wrapText = TRUE,
horizontal = "ALIGN_CENTER",
vertical = "VERTICAL_CENTER")
)
It works with orange, grey, blue, but not white. This may be an effort to prevent text from being invisible if the background were the default white, but I can't say for certain. Perhaps the package creator can comment.

The constants used by the xlsx package are define in these groups:
HALIGN_STYLES_
VALIGN_STYLES_
BORDER_STYLES_
FILL_STYLES_
CELL_STYLES_
INDEXED_COLORS_
So, just displaying them in the console for INDEX_COLORS_ you get
BLACK WHITE RED BRIGHT_GREEN BLUE YELLOW
8 9 10 11 12 13
PINK TURQUOISE DARK_RED GREEN DARK_BLUE DARK_YELLOW
14 15 16 17 18 19
VIOLET TEAL GREY_25_PERCENT GREY_50_PERCENT CORNFLOWER_BLUE MAROON
20 21 22 23 24 25
LEMON_CHIFFON ORCHID CORAL ROYAL_BLUE LIGHT_CORNFLOWER_BLUE SKY_BLUE
26 28 29 30 31 40
LIGHT_TURQUOISE LIGHT_GREEN LIGHT_YELLOW PALE_BLUE ROSE LAVENDER
41 42 43 44 45 46
TAN LIGHT_BLUE AQUA LIME GOLD LIGHT_ORANGE
47 48 49 50 51 52
ORANGE BLUE_GREY GREY_40_PERCENT DARK_TEAL SEA_GREEN DARK_GREEN
53 54 55 56 57 58
OLIVE_GREEN BROWN PLUM INDIGO GREY_80_PERCENT AUTOMATIC
59 60 61 62 63 64
You can use numeric or alias style:
cs2 <- CellStyle(wb) +
Font(
wb,
heightInPoints = 12,
isBold = F,
isItalic = F,
name = "Arial",
color="ORANGE"
)
cs2 <- CellStyle(wb) +
Font(
wb,
heightInPoints = 12,
isBold = F,
isItalic = F,
name = "Arial",
color=59
)

Related

Conditional formatting with rule with value in between

I am trying to make conditional formatting for cells based on value between two values using library(openxlsx). The problem is with the first conditional formatting rule = c(0.015,0.020), it don't work.
## Dataframe
cost_table <- read.table(text = "FRUIT COST SUPPLY_RATE
1 APPLE 15 0.026377
2 ORANGE 14 0.01122
3 KIWI 13 0.004122
5 BANANA 11 0.017452
6 AVOCADO 10 0.008324 " , header = TRUE)
## This is the line where I label the %.
cost_table$SUPPLY_RATE <- label_percent(accuracy = 0.01)(cost_table$SUPPLY_RATE)
## Creating workbook and sheet
Fruits_Table <- createWorkbook()
addWorksheet(Fruits_Table,"List 1")
writeData(Fruits_Table,"List 1",cost_table)
## Style color for conditional formatting
posStyle <- createStyle(fontColour = "#006100", bgFill = "#C6EFCE")
negStyle <- createStyle(fontColour = "#9C0006", bgFill = "#FFC7CE")
## Here is the error
conditionalFormatting(Fruits_Table, "List 1",
cols = 3,
rows = 2:6, rule = c(0.015,0.020), style = posStyle, type='between'
)
conditionalFormatting(Fruits_Table, "List 1",
cols = 3,
rows = 2:6, rule = ">0.020", style = negStyle
)
Replace this line
cost_table$SUPPLY_RATE <- label_percent(accuracy = 0.01)(cost_table$SUPPLY_RATE)
with this
class(cost_table$SUPPLY_RATE) <- "percentage"
You have replaced the numeric column with a character column and Excel got confused. Using percentage tells Excel to apply a percentage format to the cells.

R: Customizing Scatterplots

I am using the R programming language. I am trying to follow the answer posted in this previous stackoverflow post (scatterplot3d: regression plane with residuals) and add a "plane" to a scatterplot.
Suppose I have the following data:
my_data <- data.frame(read.table(header=TRUE,
row.names = 1,
text="
weight height age
1 2998.958 15.26611 53
2 3002.208 18.08711 52
3 3008.171 16.70896 49
4 3002.374 17.37032 55
5 3000.658 18.04860 50
6 3002.688 17.24797 45
7 3004.923 16.45360 47
8 2987.264 16.71712 47
9 3011.332 17.76626 50
10 2983.783 18.10337 42
11 3007.167 18.18355 50
12 3007.049 18.11375 53
13 3002.656 15.49990 42
14 2986.710 16.73089 47
15 2998.286 17.12075 52
"))
I adapted the code to fit my example:
library(scatterplot3d)
model_1 <- lm(age ~ weight + height, data = my_data)
# scatterplot
s3d <- scatterplot3d(my_data$height, my_data$weight, my_data$age, pch = 19, type = "p", color = "darkgrey",
main = "Regression Plane", grid = TRUE, box = FALSE,
mar = c(2.5, 2.5, 2, 1.5), angle = 55)
# regression plane
s3d$plane3d(model_1, draw_polygon = TRUE, draw_lines = TRUE,
polygon_args = list(col = rgb(.1, .2, .7, .5)))
# overlay positive residuals
wh <- resid(model_1) > 0
s3d$points3d(my_data$height, my_data$weight, my_data$age, pch = 19)
Problem: However, the "plane" appears to be absent :
Desired Result:
Can someone please show me what I am doing wrong?
Thanks
The order of height and weight caused the problem.
s3d <- scatterplot3d(my_data$weight, my_data$height,my_data$age, pch = 19, type = c("p"), color = "darkgrey",
main = "Regression Plane", grid = TRUE, box = FALSE,
mar = c(2.5, 2.5, 2, 1.5), angle = 55)
# regression plane
s3d$plane3d(model_1, draw_polygon = TRUE, draw_lines = TRUE,
polygon_args = list(col = rgb(.1, .2, .7, .5)))
# overlay positive residuals
wh <- resid(model_1) > 0
s3d$points3d(my_data$height, my_data$weight, my_data$age, pch = 19)

How to loop through pack_rows in r using kableextra package?

A C
-------
KK 1
KK 3
KK 3
AA 4
AA 52
BB 33
BB 7
BB 83
DD 91
DD 10
i have a table like the one above i want to use column A and make it into groups
and use start and end index to be used in pack_rows to automate using the dataframe above.
i tried to use for loop but it didn't work it showing error in loop so how can i loop through
using below code
kbl(df,booktabs = T,longtable = T) %>%
kable_styling(latex_options = c("repeat_header"),bootstrap_options = "bordered",font_size = 7,full_width = F)%>%
row_spec(0, bold = T, color = "white", background = "#008752")%>%
pack_rows("KK", 1, 3,background = "#008000")%>%
pack_rows("AA", 4, 5,background = "#008000")
Make A column as factor with levels same as appearance. Use table in pack_rows -
library(knitr)
library(kableExtra)
df$A <- factor(df$A, unique(df$A))
kbl(df,booktabs = T,longtable = T) %>%
kable_styling(latex_options = c("repeat_header"),
bootstrap_options = "bordered",font_size = 7,full_width = F)%>%
row_spec(0, bold = T, color = "white", background = "#008752")%>%
pack_rows(index = table(df$A), background = "#008000")

Plot inside of hoverinfo in Plotly

I've a plotly bar chart with a hover event which plots another plot alongside the first one
Is there a way to have the second plot show up inside of the hoverinfo box ?
The code I used is as under:
UI
library(shiny)
library(plotly)
library(shinythemes)
library(dplyr)
library(png)
ui <- fluidPage(
theme = shinytheme("spacelab"),
h2("Coupled hover-events in plotly charts using Shiny"),
tags$hr(),
fluidRow(
column(6, plotlyOutput(outputId = "ageplot", height = "600px")),
column(6, plotlyOutput(outputId = "raceplot", height = "600px"))),
tags$hr(),
tags$blockquote("Hover over age plot for race and gender information")
)
SERVER:
server <- function(input, output){
patdata <- read.csv("Sal.csv")
boston_race<-read.csv("bostonrace.csv")
patdata$Race<-ifelse(patdata$Race=="RACE_UNKNOWN", "Unknown",ifelse(patdata$Race=="BLACK_AFRICAN_AMERICAN", "African American",ifelse(patdata$Race=="RACE_LATINO_HISPANIC", "Latino Hispanic",
ifelse(patdata$Race=="WHITE", "White",ifelse(patdata$Race=="ASIAN", "Asian",
ifelse(patdata$Race=="RACE_OTHER", "Other","Unknown"))))))
patdata$Date<-as.Date(patdata$CreateDate, format = "%m/%d/%Y")
patdata$agegroup<- ifelse(patdata$Age>=0 &patdata$Age<=19,"<20",
ifelse(patdata$Age>=20 &patdata$Age<=29,"20-29",
ifelse(patdata$Age>=30 &patdata$Age<=39,"30-39",
ifelse(patdata$Age>=40 &patdata$Age<=49,"40-49",
ifelse(patdata$Age>=50,"50+","Invalid Age")))))
patdata$dp<- ifelse(patdata$Age>=0 &patdata$Age<=19,0,
ifelse(patdata$Age>=20 &patdata$Age<=29,1,
ifelse(patdata$Age>=30 &patdata$Age<=39,2,
ifelse(patdata$Age>=40 &patdata$Age<=49,3,
ifelse(patdata$Age>=50,4,NA)))))
patdata$dp<-as.numeric(patdata$dp)
patdata_age<- subset(patdata, select="agegroup")
patdata_age<-as.data.frame(table(patdata_age))
selection<-patdata_age
output$ageplot <- renderPlotly({
colnames(selection)<-c("agegroup","Freq")
selection$y<-round((patdata_age$Freq*100/sum(patdata_age$Freq)))
plot_ly(source = "source",selection, x = ~agegroup, y = selection$y, type = 'bar',
marker = list(color = 'rgb(255,140,0)',
# marker = list(color,alpha = d),
line = list(color = 'rgb(8,48,107)', width = 1.5))) %>%
layout(title = paste0("Age-group distribution of patients "),xaxis = list(title = 'age group'),
yaxis = list(title = paste0('Percentage of Patients')),titlefont=list(size=13),
annotations = list(x = ~agegroup, y = selection$y, text = paste0(selection$y, "%"),
xanchor = 'center', yanchor = 'bottom',
showarrow = FALSE))
})
output$raceplot <- renderPlotly({
eventdata <- event_data("plotly_hover", source = "source")
validate(need(!is.null(eventdata), "Hover over the age plot to populate this race plot"))
datapoint <- as.numeric(eventdata$pointNumber)[1]
sel<-patdata %>% filter(dp %in% datapoint)
raceselection<-subset(sel,select="Race")
raceselection<-as.data.frame(table(raceselection))
colnames(raceselection)<-c("Race","Freq")
raceselection$y<-round((raceselection$Freq*100/sum(raceselection$Freq)))
raceall<-merge(raceselection,boston_race)
raceall$Race<- as.character(raceall$Race)
raceall$Percent<-round(raceall$Percent,0)
plot_ly(raceall, x = ~Race, y = ~Percent, type = 'bar', name = 'Total Population',marker = list(color = 'rgb(255,140,0)',
line = list(color = 'rgb(8,48,107)', width = 1))
) %>%
add_trace(y = ~y, name = 'Patient Population',marker = list(color = 'rgb(49,130,189)',
line = list(color = 'rgb(8,48,107)', width = 1))) %>%
layout(yaxis = list(title = 'Population Percent'), barmode = 'group',
title = paste0("Patient Race comparison"))
})
}
boston_race dataset:
Race Percent
White 47
Unknown 0
Other 1.8
Latino Hispanic 17.5
Asian 8.9
African American 22.4
Sal data snippet:
CreateDate Age Race
1/6/1901 20 RACE_LATINO_HISPANIC
1/21/1901 37 BLACK_AFRICAN_AMERICAN
1/21/1901 51 WHITE
1/31/1901 58 WHITE
2/2/1901 24 ASIAN
2/4/1901 31 WHITE
2/7/1901 29 WHITE
2/7/1901 19 WHITE
2/11/1901 7 BLACK_AFRICAN_AMERICAN
2/12/1901 41 ASIAN
2/13/1901 22 WHITE
2/19/1901 3 RACE_LATINO_HISPANIC
2/24/1901 19 WHITE
3/7/1901 26 WHITE
3/12/1901 21 RACE_UNKNOWN
3/17/1901 39 RACE_LATINO_HISPANIC
3/18/1901 71 WHITE
3/20/1901 65 WHITE
4/10/1901 19 WHITE
4/18/1901 31 WHITE
4/23/1901 63 WHITE
4/24/1901 20 WHITE
4/29/1901 19 WHITE
4/30/1901 27 WHITE
5/2/1901 23 WHITE
5/12/1901 21 WHITE
5/16/1901 26 RACE_LATINO_HISPANIC
5/20/1901 54 BLACK_AFRICAN_AMERICAN
5/20/1901 2 WHITE
5/20/1901 9 RACE_LATINO_HISPANIC
5/21/1901 28 WHITE
5/29/1901 2 BLACK_AFRICAN_AMERICAN
5/30/1901 0 WHITE
6/3/1901 21 WHITE
6/9/1901 10 ASIAN
6/9/1901 37 WHITE
The current output:
I want the second plot to appear in a small hoverinfo box

Plot values are not being generated by my code using R studio, plotly in R, and 'parcoords'

I'm having trouble with plotly in R and 'parcoords'. I'm trying to plot using colorscale defined by Persona. Persona has values of 1 through 4 and I expect each number to have it's own color. The plot scales fine but there are no lines representing the values for each variable.
Here is the code
options(viewer=NULL)
p <- df %>%
plot_ly(type = 'parcoords',
line = list(color = ~Persona,
colorscale = list(c(0,'red'),c(0.5,'green'),c(1,'blue'),c(1.5,'yellow'))) ,
dimensions = list(
list(range = c(15,55),
label = 'Rescuer Count', values = ~RescuerCount),
list(range = c(15,50),
label = 'Rescuer Share', values = ~RescuerShare),
list(range = c(5,95),
label = 'Avg Serviced Zip Codes', values = ~AvgServZips),
list(range = c(10,925),
label = 'Avg Number of Rescues', values = ~ AAvgNumofRescues),
list(range = c(310,16000),
label = 'Avg Rescuer Earnings', values = ~ AAEarnings),
list(range = c(1,55),
label = 'Persona Share of Earnings', values = ~ EarnShare),
list(range = c(30,95),
label = ' Login Percentage', values = ~ LoginPrct),
list(range = c(7,95),
label = 'Prct of Login Days W/Offer', values = ~ PrctLoginDaysWO),
list(range = c(1,5),
label = 'Avg Acceptance Rate', values = ~ AvgAcceptRate),
list(range = c(150,1975),
label = 'Annualized Number of Offers', values = ~ ANumofOffers)
)
)
print(p)
Data Table is here
Persona RescuerCount RescuerShare AvgServZips AAvgNumofRescues AAEarnings EarnShare LoginPrct PrctLoginDaysWO AvgAcceptRate ANumofOffers
1 16 15 45 389 6706 27 71 91 30 1314
2 13 15 90 915 15805 51 91 94 47 1954
3 30 27 28 147 2429 18 55 86 22 679
4 51 46 6 20 319 4 34 75 13 152
resulting plot
Please Help

Resources