R ggplot2: adding custom text to legend and value counts on sides of the heat map - ggplot2

My input data looks like:
COMPANY DOMAIN REVIEW PROGRESS
Company A Service Good +
Company A Response Good +
Company A Delay Very Good
Company A Cost Poor -
Company B Service Poor -
Company B Delay Average
Company B Cost Good +
Company C Service Very Poor +
Company C Cost Average
I produced a heat map in which I add some text (value of the "PROGRESS" variable - i.e. plus or minus sign).
Here is my code:
require("ggplot2")
graph <- read.table("input.tab", header=T, sep="\t")
ggplot(data=graph, aes(x=COMPANY, y=DOMAIN, group=REVIEW, fill=REVIEW)) +
geom_tile() +
geom_text(aes(x=COMPANY, y=DOMAIN, label=PROGRESS)) +
scale_x_discrete(expand = c(0, 0)) +
scale_y_discrete(expand = c(0, 0)) +
geom_vline(xintercept=seq(1.5, length(graph$COMPANY)+0.5)) +
geom_hline(yintercept=seq(1.5, length(graph$DOMAIN)+0.5)) +
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_blank(),
axis.ticks = element_blank(),
panel.background = element_blank(),
plot.background = element_blank(),
axis.title=element_blank(),
axis.text.x = element_text(angle=45, size=12, hjust=1)
)
However I am struggling adding (see figure modified manually below):
(1) the following "PROGRESS" legend as part of the color code already listed:
+ Better
- Worse
(2) the count of data available on each row between the right side of the plot and the legend
(3) the count of data available on each column on top of the plot
Any advice?

Here's my proposed solution, I added comments in the code for you to understand what I did. There is probably a better way of generating the grid, though. Hope it helps.
graph <- read_csv(
"COMPANY ,DOMAIN ,REVIEW ,PROGRESS
Company A ,Service ,Good ,+
Company A ,Response ,Good ,+
Company A ,Delay ,Very Good ,
Company A ,Cost ,Poor ,-
Company B ,Service ,Poor ,-
Company B ,Delay ,Average ,
Company B ,Cost ,Good ,+
Company C ,Service ,Very Poor ,+
Company C ,Cost ,Average ,")
ggplot() +
# moved aesthetics and data to each geom,
# if you keep them in the ggplot call,
# you have to specify `inherit.aes = FALSE` in the rest of the geoms
geom_tile(data = graph,
aes(x = COMPANY,
y = DOMAIN,
fill = REVIEW)) +
# changed from `geom_text` to `geom_point` with custom shapes
geom_point(data = graph,
aes(x = COMPANY,
y = DOMAIN,
shape = factor(PROGRESS, labels = c("Worse", "Better"))),
size = 3) +
# custom shape scale
scale_shape_manual(name = "", values = c("-", "+")) +
# calculate marginal totals "on the fly"
# top total
geom_text(data = summarize(group_by(graph, COMPANY),
av_data = length(!is.na(PROGRESS))),
aes(x = COMPANY,
y = length(unique(graph$DOMAIN)) + 0.7,
label = av_data)) +
# right total
geom_text(data = summarize(group_by(graph, DOMAIN),
av_data = length(!is.na(PROGRESS))),
aes(x = length(unique(graph$COMPANY)) + 0.7,
y = DOMAIN, label = av_data)) +
# expand the plotting area to accomodate for the marginal totals
scale_x_discrete(expand = c(0, 0.8)) +
scale_y_discrete(expand = c(0, 0.8)) +
# changed to `geom_segment` to generate the grid, otherwise grid extends
# beyond the heatmap
# horizontal lines
geom_segment(aes(y = rep(0.5, 1 + length(unique(graph$COMPANY))),
yend = rep(length(unique(graph$DOMAIN)) + 0.5,
1 + length(unique(graph$COMPANY))),
x = seq(0.5, 1 + length(unique(graph$COMPANY))),
xend = seq(0.5, 1 + length(unique(graph$COMPANY))))) +
# vertical lines
geom_segment(aes(x = rep(0.5, 1 + length(unique(graph$DOMAIN))),
xend = rep(length(unique(graph$COMPANY)) + 0.5,
1 + length(unique(graph$DOMAIN))),
y = seq(0.5, 1 + length(unique(graph$DOMAIN))),
yend = seq(0.5, 1 + length(unique(graph$DOMAIN))))) +
# custom legend order
guides(fill = guide_legend(order = 1),
shape = guide_legend(order = 2)) +
# theme tweaks
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_blank(),
axis.ticks = element_blank(),
panel.background = element_blank(),
plot.background = element_blank(),
axis.title = element_blank(),
axis.text.x = element_text(angle = 45,
size = 12,
hjust = 1,
# move text up 20 pt
margin = margin(-20,0,0,0, "pt")),
# move text right 20 pt
axis.text.y = element_text(margin = margin(0,-20,0,0, "pt"))
)

Related

Why are Y axis labels offset in ggplot?

The Y axis labels are offset
The Y axis labels from 100 to the top are aligned to the right, while from 90 to the bottom are aligned to the left. I've looked at many paramaters and I couldn't find one to be causing this. Also, I haven't found anyone else with this same issue.
Here's my code:
test <- ggplot(data,
aes(x=Month, y=Value, color=Name, group=Name, fill=Name))+
geom_line(size=3)+
geom_point(size=5)+
scale_color_manual(values=c("#FBE785","#0F5F00","#FFC300","#1BFFAA"))+
ylab ("")+
xlab ("")+
labs(caption = paste("Fonte: Fred e IBGE.")) +
scale_x_date(date_labels = "%b/%y", breaks = "6 month", expand=c(0,0))+
coord_cartesian(clip = "off")+
theme_minimal() +
guides(fill=guide_legend())+
theme(panel.background = element_rect(fill= "#122929",color = "#122929"),
plot.background = element_rect(fill = "#122929"),
panel.grid.major = element_line(color = "#4D4B55", size =0.1),
panel.grid.minor = element_line(color= "#4D4B55", size =0.1),
panel.grid = element_blank(),
axis.text.y = element_text(vjust = 1, hjust=-1),
axis.text.x = element_text(vjust = -1, hjust=0),
legend.title = element_blank(),
legend.position = "bottom",
legend.key.width = unit(1.5, "cm"),
plot.caption = element_text(family = "Abel",vjust = -1, hjust = 0,colour="#4D4B55", size= 30),
text = element_text(family = "Abel", color = "#4D4B55",size = 35),
plot.margin = margin(1,1,1.5,1.2, "cm"))
ggsave("./test.png", width = 21, height = 15, dpi = 300)
PS: Not sharing the data itself because I guess that's not where the problem is.
Thanks!
Your text is misaligned because of your axis.text.y argument. Change hjust to 1 and it will be properly aligned. I have provided a minimal reproducible example below.
library(tidyverse)
Month <- rep(x = month.abb, times = 10)
Value <- sample(x = 10:120, size = 120, replace = TRUE)
Name <- sample(x = LETTERS[1:4], size = 120, replace = TRUE)
data <- data.frame(Month, Value, Name)
ggplot(data, aes(x = Month, y = Value, color = Name, group = Name, fill = Name)) +
geom_line(size = 1) + geom_point(size = 2) +
theme(axis.text.y = element_text(vjust = 1, hjust = 1)) # <- problem here

Mismatch when using ggplot2 with a geom_point conditional fill

I am trying to have a white fill, for models where the p.fdr variable is <0.05.
However, the code I have written, is not modifying the correct point (the blue estimate should have a white fill not the pink estimate, as pictured below).
Example code:
conf.low <- sort(runif(6, min = 0, max = 1))
conf.high <- sort(runif(6, min = conf.low[1], max = 1))
estimate <- (conf.low + conf.high) / 2
forestplot <- data.frame(
outcome = c("mean_ssrt_0","mean_ssrt_0", "strp_scr_mnrt_congr", "strp_scr_mnrt_congr", "nihtbx_picvocab_theta_0","nihtbx_picvocab_theta_0"),
measure = c("Stop-Signal Task", "Stop-Signal Task","Emotional Word-Emotional Face Stroop", "Emotional Word-Emotional Face Stroop","NIH Toolbox® Cognition Battery", "NIH Toolbox® Cognition Battery" ),
a_model = c("1", "2", "1", "2", "1", "2"),
conf.low = conf.low,
conf.high = conf.high,
estimate = estimate,
p.fdr = runif(6, min = 0.05 / 1.3, max = 0.1))
forestplot$outcome <- factor(forestplot$outcome, levels=c('mean_ssrt_0', 'strp_scr_mnrt_congr', 'nihtbx_picvocab_theta_0'),
labels=c("Mean SSRT", "RT", "PVT \n (Theta)"))
forestplot$measure <- factor(forestplot$measure, levels=c('Stop-Signal Task',
'Emotional Word-Emotional Face Stroop',
'NIH Toolbox® Cognition Battery'))
forestplot$a_model <- factor(forestplot$a_model , levels=c("1","2"))
forestplot <- forestplot %>% arrange(measure, outcome,a_model, estimate, conf.low, conf.high)
plots <- forestplot %>%
split(.$measure) %>%
map2(.,names(.), ~ggplot(.x, aes(x = outcome, y =estimate, ymin =conf.low, ymax = conf.high,fill = as.factor(measure))) +
geom_pointrange(aes(color=a_model, shape = a_model), size=0.5, position=position_dodge2(width=0.5, reverse = TRUE), show.legend = F)+ # add group
geom_point(aes(shape = a_model), size=1.5, alpha = ifelse(.x$p.fdr < 0.05, 1, 0), position=position_dodge2(width=0.5, reverse = TRUE), show.legend = F, color="white") +
geom_hline(yintercept = 0, linetype = 'dashed', col = 'black') +
scale_y_continuous(limits = c(-0.1, 1))+
coord_flip() +
xlab('')+
ylab(expression(atop("Est. mean change (in SD units with 95% CI)", paste("per 1 SD increase in gPFS"^"lowDA"))))+
ggtitle(.y)+
theme_minimal(base_size = 11)+
guides(fill = "none") +
scale_color_manual(labels = c("Model 1", "Model 2"), values = c("#00B8E7", "#F8766D")) +
labs(color="Model")+
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.title.position = "plot",
plot.title = element_text(size = 10,face="bold"), text = element_text(size = 10)))
plot <-plot_grid(plots$`Stop-Signal Task`+ ggtitle(bquote(bold(~ "Stop-Signal Task" ~ '')))+ theme(legend.position = "none", axis.title.x = element_blank(), axis.ticks.x = element_blank(), axis.text.x = element_blank(),axis.line.y = element_line(color="black", size = 0.5)),
plots$`Emotional Word-Emotional Face Stroop` + ggtitle(bquote(bold(~ 'Stroop - EWEFS' ~ ''))) + theme(legend.position = "none", axis.title.x = element_blank(), axis.ticks.x = element_blank(), axis.text.x = element_blank(),axis.line.y = element_line(color="black", size = 0.5)),
plots$`NIH Toolbox® Cognition Battery` + ggtitle(bquote(bold(~ "NIH Toolbox\U00AE" ~ ''))) + theme(legend.position = "none", axis.ticks.x = element_line(color="black", size = 0.5), axis.line.x = element_line(color="black", size = 0.5),axis.line.y = element_line(color="black", size = 0.5)),
ncol = 1, nrow=3, rel_heights = c(1,1,1), align = 'v') # add 1 col and then the number of rows = to number of plots
plot
I have tried arranging the ordering the original dataframe but, it doesn't solve the problem.
forestplot <- forestplot %>% arrange(measure, outcome, a_model, estimate, conf.low, conf.high)
Is it okay if instead of white fill, it's just transparent? You can control that through the shape argument. It also simplifies the code a little bit. This is how you would modify your plots object:
plots <- forestplot %>%
mutate(
shape = if_else(a_model == 1 & p.fdr < 0.05, "hollow_circle",
if_else(a_model == 1 & p.fdr >= 0.05, "filled_circle",
if_else(a_model == 2 & p.fdr < 0.05, "hollow_triangle", "filled_triangle")))
) %>%
split(.$measure) %>%
map2(.,names(.), ~ggplot(.x, aes(x = outcome, y = estimate, ymin = conf.low, ymax = conf.high, shape = shape, color = a_model)) +
geom_pointrange(size = 0.5, position = position_dodge2(width = 0.5, reverse = TRUE), show.legend = F) + # add group
geom_hline(yintercept = 0, linetype = 'dashed', col = 'black') +
scale_y_continuous(limits = c(-0.1, 1)) +
scale_shape_manual(values = c("filled_circle" = 16, "hollow_triangle" = 2, "hollow_circle" = 1, "filled_triangle" = 17)) +
coord_flip() +
xlab('')+
ylab(expression(atop("Est. mean change (in SD units with 95% CI)", paste("per 1 SD increase in gPFS"^"lowDA"))))+
ggtitle(.y)+
theme_minimal(base_size = 11)+
guides(fill = "none") +
scale_color_manual(values = c("1" = "#00B8E7", "2" = "#F8766D")) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.title.position = "plot",
plot.title = element_text(size = 10,face="bold"), text = element_text(size = 10)))

ggplot2 Expand the plot limits giving error

I have a df:
test<- data.frame (Metrics = c("PCT_PF_READS (%)" , "PCT_Q30_R1 (%)" , "PCT_Q30_R2 (%)"),
LowerLimit = c(80,80,80),
Percent = c(93.1,95.1,92.4)
)
> test
Metrics LowerLimit Percent
1 PCT_PF_READS (%) 80 93.1
2 PCT_Q30_R1 (%) 80 95.1
3 PCT_Q30_R2 (%) 80 92.4
I am trying to plot in ggplot2 but I want to specify the yaxis.
If I do:
ggplot(data=test3, aes(x= Metrics,y=Percent,)) +
geom_bar(stat="identity" )
If I try to set the yaxis to start at 75, I get a blank plot:
ggplot(data=test3, aes(x= Metrics,y=Percent,)) +
geom_bar(stat="identity" ) + scale_y_continuous(limits = c(75,100))
with the message
Warning message:
Removed 3 rows containing missing values (geom_bar)
But the values are in range????
Does this answer your question?
library(tidyverse)
test<- data.frame (Metrics = c("PCT_PF_READS (%)" , "PCT_Q30_R1 (%)" , "PCT_Q30_R2 (%)"),
LowerLimit = c(80,80,80),
Percent = c(93.1,95.1,92.4)
)
# Starting plot:
ggplot(data = test, aes(x = Metrics, y = Percent)) +
geom_bar(stat = "identity")
# If you cut off any of the bar using "limit" the bar is removed,
# E.g. this removes the middle bar (Percent = 95.1)
ggplot(data = test, aes(x = Metrics, y = Percent)) +
geom_bar(stat = "identity") +
scale_y_continuous(limits = c(0,95))
#> Warning: Removed 1 rows containing missing values (position_stack).
# A better solution is to use "coord_cartesian()"
ggplot(data = test, aes(x = Metrics, y = Percent)) +
geom_bar(stat = "identity") +
coord_cartesian(ylim = c(75, 100))
# Although it's generally advised to keep the whole axis,
# as 'chopping off' the bottom can be misleading
# Another alternative is to write the percentages on the plot:
ggplot(data = test, aes(x = Metrics, y = Percent)) +
geom_bar(stat = "identity") +
geom_text(aes(label = paste0(Percent, "%")),
nudge_y = 2)
Created on 2022-10-19 by the reprex package (v2.0.1)

Start ggplot continuous axis with a squiggly line break? [duplicate]

I have a dataframe (dat) with two columns 1) Month and 2) Value. I would like to highlight that the x-axis is not continuous in my boxplot by interrupting the x-axis with two angled lines on the x-axis that are empty between the angled lines.
Example Data and Boxplot
library(ggplot2)
set.seed(321)
dat <- data.frame(matrix(ncol = 2, nrow = 18))
x <- c("Month", "Value")
colnames(dat) <- x
dat$Month <- rep(c(1,2,3,10,11,12),3)
dat$Value <- rnorm(18,20,2)
ggplot(data = dat, aes(x = factor(Month), y = Value)) +
geom_boxplot() +
labs(x = "Month") +
theme_bw() +
theme(panel.grid = element_blank(),
text = element_text(size = 16),
axis.text.x = element_text(size = 14, color = "black"),
axis.text.y = element_text(size = 14, color = "black"))
The ideal figure would look something like below. How can I make this discontinuous axis in ggplot?
You could make use of the extended axis guides in the ggh4x package. Alas, you won't easily be able to create the "separators" without a hack similar to the one suggested by user Zhiqiang Wang
guide_axis_truncated accepts vectors to define lower and upper trunks. This also works for units, by the way, then you have to pass the vector inside the unit function (e.g., trunc_lower = unit(c(0,.45), "npc") !
library(ggplot2)
library(ggh4x)
set.seed(321)
dat <- data.frame(matrix(ncol = 2, nrow = 18))
x <- c("Month", "Value")
colnames(dat) <- x
dat$Month <- rep(c(1,2,3,10,11,12),3)
dat$Value <- rnorm(18,20,2)
# this is to make it slightly more programmatic
x1end <- 3.45
x2start <- 3.55
p <-
ggplot(data = dat, aes(x = factor(Month), y = Value)) +
geom_boxplot() +
labs(x = "Month") +
theme_classic() +
theme(axis.line = element_line(colour = "black"))
p +
guides(x = guide_axis_truncated(
trunc_lower = c(-Inf, x2start),
trunc_upper = c(x1end, Inf)
))
Created on 2021-11-01 by the reprex package (v2.0.1)
The below is taking user Zhiqiang Wang's hack a step further. You will see I am using simple trigonometry to calculate the segment coordinates. in order to make the angle actually look as it is defined in the function, you would need to set coord_equal.
# a simple function to help make the segments
add_separators <- function(x, y = 0, angle = 45, length = .1){
add_y <- length * sin(angle * pi/180)
add_x <- length * cos(angle * pi/180)
## making the list for your segments
myseg <- list(x = x - add_x, xend = x + add_x,
y = rep(y - add_y, length(x)), yend = rep(y + add_y, length(x)))
## this function returns an annotate layer with your segment coordinates
annotate("segment",
x = myseg$x, xend = myseg$xend,
y = myseg$y, yend = myseg$yend)
}
# you will need to set limits for correct positioning of your separators
# I chose 0.05 because this is the expand factor by default
y_sep <- min(dat$Value) -0.05*(min(dat$Value))
p +
guides(x = guide_axis_truncated(
trunc_lower = c(-Inf, x2start),
trunc_upper = c(x1end, Inf)
)) +
add_separators(x = c(x1end, x2start), y = y_sep, angle = 70) +
# you need to set expand to 0
scale_y_continuous(expand = c(0,0)) +
## to make the angle look like specified, you would need to use coord_equal()
coord_cartesian(clip = "off", ylim = c(y_sep, NA))
I think it is possible to get what you want. It may take some work.
Here is your graph:
library(ggplot2)
set.seed(321)
dat <- data.frame(matrix(ncol = 2, nrow = 18))
x <- c("Month", "Value")
colnames(dat) <- x
dat$Month <- rep(c(1,2,3,10,11,12),3)
dat$Value <- rnorm(18,20,2)
p <- ggplot(data = dat, aes(x = factor(Month), y = Value)) +
geom_boxplot() +
labs(x = "Month") +
theme_bw() +
theme(panel.grid = element_blank(),
text = element_text(size = 16),
axis.text.x = element_text(size = 14, color = "black"),
axis.text.y = element_text(size = 14, color = "black"))
Here is my effort:
p + annotate("segment", x = c(3.3, 3.5), xend = c(3.6, 3.8), y = c(14, 14), yend = c(15, 15))+
coord_cartesian(clip = "off", ylim = c(15, 25))
Get something like this:
If you want to go further, it may take several tries to get it right:
p + annotate("segment", x = c(3.3, 3.5), xend = c(3.6, 3.8), y = c(14, 14), yend = c(15, 15))+
annotate("segment", x = c(0, 3.65), xend = c(3.45, 7), y = c(14.55, 14.55), yend = c(14.55, 14.55)) +
coord_cartesian(clip = "off", ylim = c(15, 25)) +
theme_classic()+
theme(axis.line.x = element_blank())
Just replace axis with two new lines. This is a rough idea, it may take some time to make it perfect.
You could use facet_wrap. If you assign the first 3 months to one group, and the other months to another, then you can produce two plots that are side by side and use a single y axis.
It's not exactly what you want, but it will show the data effectively, and highlights the fact that the x axis is not continuous.
dat$group[dat$Month %in% c("1", "2", "3")] <- 1
dat$group[dat$Month %in% c("10", "11", "12")] <- 2
ggplot(data = dat, aes(x = factor(Month), y = Value)) +
geom_boxplot() +
labs(x = "Month") +
theme_bw() +
theme(panel.grid = element_blank(),
text = element_text(size = 16),
axis.text.x = element_text(size = 14, color = "black"),
axis.text.y = element_text(size = 14, color = "black")) +
facet_wrap(~group, scales = "free_x")
* Differences in the plot are likely due to using different versions of R where the set.seed gives different result

Add boxes with descriptive annotations to y-axis in ggplot2

I"M trying to add another label or description to my Y axis. I attached a picture for reference for what I'm trying to accomplish. I can't find anything that describes how to add additional elements to an axis. It the "Good" and "Bad" boxes beside the Y axis that I"m trying to incorporate into my ggplot. Thanks!
enter image description here
One approach to achieve this is by using patchwork. You can set up the annotations of the y-axis as a second ggplot and glue it to your main plot using patchwork. Try this:
library(ggplot2)
library(patchwork)
library(dplyr)
p1 <- tibble(x = 1:10, y = 1:10) %>%
ggplot(aes(x, y)) +
geom_point() +
scale_y_reverse(breaks = seq(1, 10)) +
labs(y = NULL)
p2 <- tibble(ymin = c(0, 4), ymax = c(4, 10), fill = c("bad", "good")) %>%
ggplot() +
geom_rect(aes(xmin = 0, xmax = 1, ymin = ymin, ymax = ymax, fill = fill)) +
geom_text(aes(x = .5, y = (ymin + ymax) / 2, label = fill), angle = 90) +
scale_y_reverse(breaks = seq(1, 10), expand = expansion(mult = c(0, 0))) +
scale_x_continuous(breaks = c(0), expand = expansion(mult = c(0, 0))) +
guides(fill = FALSE) +
theme_void()
p2 + p1 + plot_layout(widths = c(1, 9))
Created on 2020-05-28 by the reprex package (v0.3.0)