R Hourly Heatmap with adjusted Dates - r

I'm new to r and tried the hourly heatmapt from the r grah gallery:
https://r-graph-gallery.com/283-the-hourly-heatmap.html
My question is, if it possible to adjust it that way, that the x axis ish shown with the correct amount of days in the month(example: Jan 1 … 31, Feb 1 … 28)
I tried to change scale_x_continuos with scale_x_date but it didnt worked as expected.

You can amend the code as folows, using a custom labelling function in scale_x_continuous:
ggplot(df, aes(day, hour, fill = temp)) +
geom_tile(color = "white",size = 0.1) +
scale_fill_viridis(name = "Hrly Temps C", option = "C") +
facet_grid(year~month, scales = 'free_x') +
scale_y_continuous(trans = "reverse", breaks = unique(df$hour)) +
scale_x_continuous(breaks = ~c(1, 10, 20, floor(max(.x, na.rm = TRUE)) -2)) +
theme_minimal(base_size = 8) +
labs(title= paste("Hourly Temps - Station", statno), x = "Day",
y = "Hour Commencing") +
theme(legend.position = "bottom",
plot.title = element_text(size = 14, hjust = 0),
axis.text.y = element_text(size = 6),
strip.background = element_rect(colour = "white"),
axis.ticks = element_blank(),
axis.text = element_text(size = 7),
legend.title = element_text(size = 8),
legend.text = element_text(size = 6)) +
removeGrid()

Related

Set time series limits using scale_x_datetime in R

I am making a time series figure in ggplot2 and would like to set limits for the x-axis. When I try to set the limits using scale_x_datetime(limits = ...), dates beyond the limits are shown, how can I avoid this? I have tried using answers found in similar SO questions (similar 1, similar 2) but have not had success.
Example Data:
library(ggplot2)
library(lubridate)
df <- data.frame(matrix(ncol = 2, nrow = 70176))
colnames(df)[1:2] <- c("DateTime","Value")
df$DateTime <- seq(ymd_hm('2020-01-01 00:00'),ymd_hm('2021-12-31 23:45'), by = '15 mins')
df$Value <- rnorm(70176,100,20)
This attempt comes from the first similar SO question
lims <- as.POSIXct(strptime(c("2020-01-01 00:00","2021-12-31 23:45"), format = "%Y-%m-%d %H:%M"))
ggplot(df, aes(x = DateTime, y = Value)) +
geom_line() +
scale_x_datetime(date_labels = "%b %d %Y",
date_breaks = "1 month",
limits = lims) +
labs(x = "",
y = "Value") +
theme_bw() +
theme(panel.grid = element_blank(),
text = element_text(size = 16, color = "black"),
axis.text.x = element_text(size = 16, color = "black", angle = 90, vjust = 0.5, hjust = 1),
axis.text.y = element_text(size = 16, color = 'black'))
This attempt comes from the second similar SO question
ggplot(df, aes(x = DateTime, y = Value)) +
geom_line() +
scale_x_datetime(date_labels = "%b %d %Y",
date_breaks = "1 month",
limits = c(min(df$DateTime), max(df$DateTime))) +
labs(x = "",
y = "Value") +
theme_bw() +
theme(panel.grid = element_blank(),
text = element_text(size = 16, color = "black"),
axis.text.x = element_text(size = 16, color = "black", angle = 90, vjust = 0.5, hjust = 1),
axis.text.y = element_text(size = 16, color = 'black'))
The ideal figure would not display dates outside of the limits of the data (i.e., Dec 2019 or Jan 2022).
#JonSpring suggestion of using scale_x_datetime(..., expand = expansion(add = c(0,0))) answered my question. Below is the code using the example dataset for others who might come across this question.
lims <- as.POSIXct(strptime(c("2019-12-15 00:00","2022-01-15 23:45"), format = "%Y-%m-%d %H:%M"))
ggplot(df, aes(x = DateTime, y = Value)) +
geom_line() +
scale_x_datetime(date_labels = "%b %d %Y",
date_breaks = "1 month",
limits = lims,
expand = expansion(add = c(0,0))) +
labs(x = "",
y = "Value") +
theme_bw() +
theme(panel.grid = element_blank(),
text = element_text(size = 16, color = "black"),
axis.text.x = element_text(size = 16, color = "black", angle = 90, vjust = 0.5, hjust = 1),
axis.text.y = element_text(size = 16, color = 'black'))
Using expand = c(0,0) in scale_x_datetime() will remove extra space.

Waffle chart with time on x axis

I would like to plot a waffle chart with time on the x-axis in R, similar to this one below. Can anyone help, please? Thanks.
The dataset is here:
df <- data.frame(spec = c("Rehab", "Cardiology", "Endocrine", "Respiratory", "General Surgery"),
start.month = c(11,11,7,3,1) )
Perhaps something like this?
library(ggplot2)
df2 <- do.call(rbind, lapply(seq(nrow(df)), function(i)
data.frame(month = factor(month.abb[12:df$start.month[i]], levels = month.abb),
spec = df$spec[i])))
df2$spec <- factor(df2$spec, levels = names(rev(sort(table(df2$spec)))))
ggplot(df2, aes(month, spec, colour = spec)) +
geom_point(size = 8, shape = 15) +
coord_cartesian(ylim = c(1, 9)) +
labs(y = "Cumulative no. of specialties",
x = "Months",
colour = "Specialties") +
scale_color_manual(values = c("#ffc000", "#ed7d31", "#5a9bd5",
"#70ad46", "#44546b")) +
theme_classic() +
theme(axis.text.y.left = element_blank(),
axis.ticks.length.y = unit(0, "points"),
legend.background = element_rect(colour = "black"),
axis.text = element_text(size = 16),
axis.title = element_text(size = 16))

ggplot: Using geom_col with facet_wrap

I have been using R for 6 months now (fairly new).
I have created a nice graph using the facet_wrap funciton, with geom_point.
However, i don't seem to have success with geom_col, when plotting another parameter i am interested in.
The code is below:
T <- Titers %>%
ggplot(aes(Sample_ID, Titer)) +
geom_col(aes(col=Day), size=1.1) +
facet_wrap(Strategy~Additives) +
scale_color_manual(values = Ahmad) +
ylab('Titer mg/L') +
xlab('Time (Day)') +
ggtitle('All data') +
geom_label_repel(aes(label = Sample_ID), data = tail(Titers, 14), nudge_x =
2, direction = "y", segment.size = 0.2, hjust = 0) + theme(strip.text.x =
element_text(size = 12), axis.title = element_text(size = 14), axis.text =
element_text(size = 14), legend.position = "none")
The code that have been working fine is the following:
Q2 <- USP20005 %>%
ggplot(aes(Day, Diameter)) +
geom_line(aes(col=Sample_ID), size=1.1) +
facet_wrap(Strategy~Additives) +
scale_color_manual(values = Ahmad) +
ylab('VCD E6 cells/mL') +
xlab('Time (Day)') +
ggtitle('All data') +
geom_label_repel(aes(label = Sample_ID), data = tail(USP20005, 24), nudge_x
= 2, direction = "y", segment.size = 0.2, hjust = 0) +
theme(strip.text.x = element_text(size = 12), axis.title = element_text(size =
14), axis.text = element_text(size = 14), legend.position = "none") +
scale_x_continuous(breaks = seq(0, 14, 2), limits = c(0, 14)) +
scale_y_continuous(breaks = seq(10, 20, 2), limits = c(10, 20))
Why are there spaces vetween the columns, even though i used facet_warp to split the samples into different boxes (it seems R is still reserving the empty spots?)
Just to be clear: I want to see every 2-4 samples together in on box, where the bars for each sample on the different days are stuck to each other. I WAS able to plot them stacked, but i dont want that.
What am I doing wrong here? Any help would be much appreciated.
Thank you in advance
Ahmad
If you use scale_x_*(), the x-axis will be fixed and maintain the spaces.

Partial italics in facet headings of ggplot

I am wondering if there is any way to rename facet titles so that they contain partial italics and partial non-italics.
Here is some toy data
library(Hmisc)
library(dplyr)
# Plot power vs. n for various odds ratios
n <- seq(10, 1000, by=10) # candidate sample sizes
OR <- as.numeric(sort(c(seq(1/0.90,1/0.13,length.out = 9),2.9))) # candidate ORs
alpha <- c(.001, .01, .05) # alpha significance levels
# put all of these into a dataset and calculate power
powerDF <- data.frame(expand.grid(OR, n, alpha)) %>%
rename(OR = Var1, num = Var2, alph = Var3) %>%
arrange(OR) %>%
mutate(power = as.numeric(bpower(p1=.29, odds.ratio=OR, n=num, alpha = alph))) %>%
transform(OR = factor(format(round(OR,2),nsmall=2)),
alph = factor(ifelse(alph == 0.001, "p=0.001",
ifelse(alph == 0.01, "p=0.01", "p=0.05"))))
pPower <- ggplot(powerDF, aes(x = num, y = power, colour = factor(OR))) +
geom_line() +
facet_grid(factor(alph)~.) +
labs(x = "sample size") +
scale_colour_discrete(name = "Odds Ratio") +
scale_x_continuous(breaks = seq(0,1000,100)) +
scale_y_continuous(breaks = seq(0,1,.1), sec.axis = sec_axis(trans=I, breaks=NULL, name="Significance Level")) + # this is the second axis label
theme_light() +
theme(axis.title.x = element_text(size = 12, face = "bold"),
axis.title.y = element_text(size = 12, face = "bold"),
axis.text = element_text(size = 11),
panel.grid.minor = element_blank(),
panel.grid.major.y = element_line(colour = "gray95"),
panel.grid.major.x = element_line(colour = "gray95"),
strip.text = element_text(colour = 'black', face = 'bold', size = 12),
legend.text = element_text(size = 12),
legend.title = element_text(size = 12, face = "bold"))
pPower
Is there any way to get the facet headings to read "p=0.001", "p=0.01" etc, instead of "p=0.001", i.e. to get partial italics and partial non-italics?

R - ggplot2 - bar chart - series get incorrect value labels

I am trying to plot a basic stack bar chart to present number of acceptations and rejections for n simulations. (one column)
How can I control which series gets on the top of the stack together with corresponding value label?
I tried two versions neither had worked. Either colors are wrong or the labels.
Version 1
#version 1
T <- c(1,0)
H0_Testing <- c("Accept","Reject")
Counter <- c(100,900)
Label= c("L","L")
barplotdata<- data.frame(H0_Testing,T,Counter,Label)
fill <- c("#E1B378","#5F9EA0")
chartlabels=c("Accepted1","Rejected1")
title="version 1"
#Ploting
ggplot(barplotdata,aes(x=Label,y=Counter,fill=factor(T))) + geom_bar(stat ="identity",width=.2)+
geom_text(data=barplotdata, aes(label =Counter, y = Counter, size=4), show_guide = F)+
scale_fill_manual(labels=chartlabels, values=fill) +
theme(legend.title = element_blank()) +
theme(plot.title = element_text(size = 10),
axis.title.x = element_text(face="bold",size = 9), axis.title.y = element_text(face="bold",size = 8),
axis.text.x = element_text(size=8),axis.text.y = element_text(size=7),legend.text = element_text(size=7.5))+
ggtitle(title)
Version 2
#version 2
T <- c(0,1)
H0_Testing <- c("Reject","Accept")
Counter <- c(900,100)
Label= c("L","L")
barplotdata<- data.frame(H0_Testing,T,Counter,Label)
fill <- c("#5F9EA0","#E1B378")
chartlabels=c("Rejected2","Accepted2")
title="version 2"
#Ploting
ggplot(barplotdata,aes(x=Label,y=Counter,fill=factor(T))) + geom_bar(stat ="identity",width=.2)+
geom_text(data=barplotdata, aes(label =Counter, y = Counter, size=4), show_guide = F)+
scale_fill_manual(labels=chartlabels, values=fill) +
theme(legend.title = element_blank()) +
theme(plot.title = element_text(size = 10),
axis.title.x = element_text(face="bold",size = 9), axis.title.y = element_text(face="bold",size = 8),
axis.text.x = element_text(size=8),axis.text.y = element_text(size=7),legend.text = element_text(size=7.5))+
ggtitle(title)
New Plot:
T <- c(0,1)
H0_Testing <- c("Reject","Accept")
Counter <- c(900,100)
Label= c("L","L")
barplotdata<- data.frame(H0_Testing,T,Counter,Label)
fill <- c("#5F9EA0","#E1B378")
chartlabels=c("Rejected2","Accepted2")
title="version 2"
ggplot(barplotdata,aes(x=Label,y=Counter,fill=rev(factor(Counter)))) + geom_bar(stat ="identity",width=.2)+
geom_text(data=barplotdata, aes(label =rev(factor(Counter)), size=4), show.legend = F)+
scale_fill_manual(labels=chartlabels, values=fill) +
theme(legend.title = element_blank()) +
theme(plot.title = element_text(size = 10),
axis.title.x = element_text(face="bold",size = 9), axis.title.y = element_text(face="bold",size = 8),
axis.text.x = element_text(size=8),axis.text.y = element_text(size=7),legend.text = element_text(size=7.5))+
ggtitle(title)
ggplot(barplotdata,aes(x=Label,y=Counter,fill=factor(Counter))) + geom_bar(stat ="identity",width=.2)+
geom_text(data=barplotdata, aes(label =rev(factor(Counter)), size=4), show.legend = F)+
scale_fill_manual(labels=c("Accepted2","Rejected2"), values=fill) +
theme(legend.title = element_blank()) +
theme(plot.title = element_text(size = 10),
axis.title.x = element_text(face="bold",size = 9), axis.title.y = element_text(face="bold",size = 8),
axis.text.x = element_text(size=8),axis.text.y = element_text(size=7),legend.text = element_text(size=7.5))+
ggtitle(title)
Finally, if you want to switch the tiles:
ggplot(barplotdata,aes(x=Label,y=rev(Counter),fill=factor(Counter))) + geom_bar(stat ="identity",width=.2)+
geom_text(data=barplotdata, aes(label =rev(factor(Counter)), size=4), show.legend = F)+
scale_fill_manual(labels=c("Rejected2","Accepted2"), values=fill) +
theme(legend.title = element_blank()) +
theme(plot.title = element_text(size = 10),
axis.title.x = element_text(face="bold",size = 9), axis.title.y = element_text(face="bold",size = 8),
axis.text.x = element_text(size=8),axis.text.y = element_text(size=7),legend.text = element_text(size=7.5))+
ggtitle(title)
Note, for this third plot I added y=rev(Counter) in the aesthetics call.
as opposed to (your original plot Version 2):
#Ploting
ggplot(barplotdata,aes(x=Label,y=Counter,fill=factor(T))) + geom_bar(stat ="identity",width=.2)+
geom_text(data=barplotdata, aes(label =Counter, y = Counter, size=4), show.legend = F)+
scale_fill_manual(labels=chartlabels, values=fill) +
theme(legend.title = element_blank()) +
theme(plot.title = element_text(size = 10),
axis.title.x = element_text(face="bold",size = 9), axis.title.y = element_text(face="bold",size = 8),
axis.text.x = element_text(size=8),axis.text.y = element_text(size=7),legend.text = element_text(size=7.5))+
ggtitle(title)
The key difference for the bars is: fill=rev(factor(T) -notice that i reversed the factor level with the rev() command. For the text, notice that I removed y=Counter from geom_text() and changed the label value to rev(factor(Counter)). Also, for the second plot I manually set the legend items.
UPDATE
As per the OP's request in the comments, "I would like to change two more formats, decrease the font of the value labels and get rid of the T below x axis. Do you know how could I do the formatting?"
To decrease the font size, move size out of the aesthetics (you can also get rid of show.legend=F or show_guide=F). To get rid of the axis label you would add theme(axis.ticks = element_blank(), axis.text.x = element_blank())+ylab("Counter") -that removes the letter L and the tick mark which is what I think you meant when you said T. The code for both within the ggplot call is:
ggplot(barplotdata,aes(x=Label,y=rev(Counter),fill=factor(Counter))) + geom_bar(stat ="identity",width=.2)+
geom_text(data=barplotdata, aes(label =rev(factor(Counter))),size=2)+
scale_fill_manual(labels=c("Rejected2","Accepted2"), values=fill) +
theme(legend.title = element_blank()) +
theme(plot.title = element_text(size = 10),
axis.title.x = element_text(face="bold",size = 9), axis.title.y = element_text(face="bold",size = 8),
axis.text.x = element_text(size=8),axis.text.y = element_text(size=7),legend.text = element_text(size=7.5))+
ggtitle(title)+theme(axis.ticks = element_blank(), axis.text.x = element_blank())+ylab("Counter")

Resources