R - add transparency to rastergrob background of a ggplot - r

I'd like to add transparency to a rastergrob object used as a ggplot background.
Here is my code
library(ggplot2)
library(grid)
library(ggthemes)
reds <- c("brown", "red","orange","green","orange","red","brown","grey")
g <- rasterGrob(reds, width = unit(1, "npc"), height = unit(1,"npc"),interpolate = TRUE)
p <- ggplot(data = economics, aes(x = date, y = unemploy)) +
annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf)+
geom_line( alpha=1, color = "white", size = 0.5 ) +
xlab("Years") + ylab("Unemployed [thousands]") +
theme_base() +
theme(panel.background=element_blank(),
plot.background=element_blank(),
line = element_line(colour="white")) +
theme()
grid.newpage()
print(p, newpage = FALSE)
I could not add an alpha in the rastergrob , neither in annotation_custom. I've been searching for a while.

scales::alpha() is one option,
grid.newpage()
grid.text("background")
reds <- c("brown", "red","orange","green","orange","red","brown","grey")
grid.raster(scales::alpha(reds, 0.5), width = unit(1, "npc"), height = unit(1,"npc"),interpolate = TRUE)

I found out one possible way to do it is to use the function adjustcolor() that takes the parameter of transparency "alpha" And your list of colors and returns a list of transparent colors

Related

Legend not changing colors in ggplot2

I am trying to plot a scatter plot with 22 variables, so they all need to have different markers. I thought of repeating some shapes and colors from RColorBrew, and everything works fine, except for the legend that does not update with the colors I selected (please see image below). I also attached a working example below. What could I possibly be doing wrong?
#!/usr/bin/env Rscript
library(ggplot2)
library(ggpubr)
library(RColorBrewer)
theme_set(
theme_pubr()
)
data <- data.frame(
x = c(1:22),
y = as.factor(c(1:22))
)
shapes <- rep(15:18, 6)
colors <- rep(brewer.pal(n = 11, name = "Paired"), 2)
plot <- ggplot(data, aes(x=x, y=y, group=y, size=9, color=colors)) +
geom_point(aes(shape=y)) +
scale_shape_manual(values=shapes) +
scale_size(guide="none") +
guides(fill="none", color="none")
plot <- plot + theme(panel.grid.major=element_line(colour="gray", size=0.2),
panel.grid.minor=element_line(colour="gray", size=0.2))
print(plot)
There are two issues:
I you want to have your colors make use of scale_color_manual and map y on the color aes as you did with shape
The reason your legend does not get colored is that you have set guides(color = "none")
library(ggplot2)
library(ggpubr)
library(RColorBrewer)
theme_set(
theme_pubr()
)
data <- data.frame(
x = c(1:22),
y = as.factor(c(1:22))
)
shapes <- rep(15:18, 6)
colors <- rep(brewer.pal(n = 11, name = "Paired"), 2)
plot <- ggplot(data, aes(x = x, y = y, group = y, size = 9)) +
geom_point(aes(shape = y, color = y)) +
scale_shape_manual(values = shapes) +
scale_color_manual(values = colors) +
scale_size(guide = "none") +
guides(fill = "none")
plot + theme(
panel.grid.major = element_line(colour = "gray", size = 0.2),
panel.grid.minor = element_line(colour = "gray", size = 0.2)
)
I found a number of things going on. I broke them down one by one here:
You're including colors in the aes but it's not a part of the data, it's just the color palette, so that shouldn't be included here. aes is telling ggplot what data to show, not how to format it.
geom_point needs both a color and shape aes argument so that it can combine them and later tell the legend how it has done so.
To control the color palette used, I added scale_color_manual, similar to how you were already using scale_shape_manual to manually adjust formatting
Remove the guides line at the end. by setting color = "none" it's blocking color from being added to the legend.
Try the segment of code below.
data <- data.frame(
x = c(1:22),
y = as.factor(c(1:22))
)
shapes <- rep(15:18, 6)
colors <- rep(brewer.pal(n = 11, name = "Paired"), 2)
#OLD: plot <- ggplot(data, aes(x=x, y=y, group=y, size=9, color=colors)) +
plot <- ggplot(data, aes(x=x, y=y, group=y, size=9)) +
#OLD: geom_point(aes(shape=y)) +
geom_point(aes(shape=y, color=y)) +
scale_shape_manual(values=shapes) +
#NEW LINE
scale_color_manual(values = colors) +
scale_size(guide="none")
# REMOVED guides(fill="none", color="none")
plot <- plot + theme(panel.grid.major=element_line(colour="gray", size=0.2),
panel.grid.minor=element_line(colour="gray", size=0.2))
print(plot)

Change orientation of grob background gradient

I was surprised that the following simple grob created from a vector of colors works almost as requested.
However, I would like to make the gradient left to right, not top to bottom.
library(ggplot2)
library(grid)
grad = colorRampPalette(c("red", "yellow"))(10)
ggplot(df, aes(x,y)) +
annotation_custom(rasterGrob(grad,
width=unit(1,"npc"),
height=unit(1,"npc"))) +
scale_x_continuous(limits = c(0,1)) +
scale_y_continuous(limits = c(0,1))
Answer is t
You have to transpose your grad vector (input to rasterGrob):
library(ggplot2)
ggplot() +
annotation_custom(rasterGrob(t(grad),
width = unit(1, "npc"), height = unit(1, "npc")))

R: ggplot background gradient coloring

I would like to generate ggplot’s with gradient coloring, filling both plot panel and its background, as herein shown.
As you can see the gradient background coloring encompasses both plot panel and its background. At the moment, only an "approximation" of the required solution is known to me:
library(ggplot2)
library(grid)
library(gridExtra)
reds <- c("#7B0664", "#E32219")
g <- rasterGrob(reds, width = unit(1, "npc"), height = unit(1, "npc"),
interpolate = TRUE)
ggplot(data = economics, aes(x = date, y = unemploy)) +
annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
geom_line( alpha=1, color = "white", size = 0.5 ) +
xlab("Years") + ylab("Unemployed [thousands]") +
theme(plot.background = element_rect(fill=reds[2]))
Using aboveshown code, the plot panel results as gradient colored within axis boundaries, however it does not span the overall background with such gradient coloring. The theme(plot.background =...) is capable to fill the remaining background, however it does not seem to be able to take advantage of gradient coloring. To remark further that same gradient coloring should be applied to the overall plot background.
Any suggestions will be appreciated. Thanks.
you can print/draw the plot on top of a rasterGrob,
library(ggplot2)
library(grid)
library(ggthemes)
reds <- c("#7B0664", "#E32219")
g <- rasterGrob(reds, width = unit(1, "npc"), height = unit(1, "npc"), interpolate = TRUE)
p <- ggplot(data = economics, aes(x = date, y = unemploy)) +
geom_line( alpha=1, color = "white", size = 0.5 ) +
xlab("Years") + ylab("Unemployed [thousands]") +
theme_base() +
theme(panel.background=element_blank(),
panel.border = element_blank(),
plot.background=element_blank(),
text = element_text(colour="white"),
line = element_line(colour="white")) +
theme()
grid.newpage()
grid.draw(g)
print(p, newpage = FALSE)

Add a customized x-axis to plot ggplot2 and y-axis as well

I have the following code:
df=data.frame(time=as.factor(rep(0.5:9.5,each=10)),
roi=rep(1:10,10),
area=runif(100, 5.0, 7.5))
df$time=factor(df$time, levels=rev(levels(df$time)))
ggplot(data=df, aes(x=factor(roi), y=time, fill = area)) +
theme_minimal() + coord_fixed(ratio=1) +
geom_tile(colour = NA, width = 1.5, height = 1) +
scale_fill_gradient(low="black",high="white")
Now, I want to remove the x-axis and add a new one to have the expected fig below. The x-axis will be divided into 4 parts for 4 segs with 39%,23%,23%,15% of axis length for Seg 1, Seg 2, Seg 3, Seg 4, respectively. Could anybody hava any idea to solve it. I apprecicate all response and am looking forward your answers.
Great thanks to Mark Heckmann for helpful answer to my problem. I would like to ask one more thing. I also want to modify the y-axis by "scale_y_discrete", the code ran well but the y-axis label did not meet my expectation. The code I ran is:
ggplot(data=df, aes(x=factor(roi), y=time, fill = area)) + theme_minimal() +coord_fixed(ratio=1) +geom_tile(colour = NA, width = 1.5, height = 1)+scale_fill_gradient(low="black",high="white") +scale_y_discrete(name="Time (min)",expand =c(0.01,0.1),breaks=c(1,2.5,5.0,7.5,10.0),labels=c(0,15,30,45,60))
Thank you very much!
You need to use annotation_custom to draw outside the plotting area.
#### your plot
library(ggplot2)
g <- ggplot(data=df, aes(x=factor(roi), y=time, fill = area)) +
theme_minimal() + coord_fixed(ratio=1) +
geom_tile(colour = NA, width = 1.5, height = 1) +
scale_fill_gradient(low="black",high="white")
Extra code:
library(grid)
# remove axis
g <- g + theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank()) +
scale_x_discrete(expand = c(0,0))
# calculate segment coordinates
segs <- c(.39, .23, .23, .15)
segs_center <- cumsum(segs) - segs/2
seg_ticks <- cumsum(segs)[1:3]
seg_labels <- paste("Seg", seq_along(segs))
# create graphicaal objects and gather as tree
grobs <- grobTree(linesGrob(c(0,1), c(.5,.5)),
segmentsGrob(x0=seg_ticks, x1=seg_ticks, y0=0, y1=1),
textGrob(x=segs_center, y=0,
label = seg_labels, hjust = .5, gp = gpar(cex =.7)))
# insert grobsTree in as annotation
g <- g + annotation_custom( grob = grobs,
ymin = -.2, ymax = .2,
xmin = .25, xmax = 10.75)
# override clipping for plotting outside of plotting area
gt <- ggplot_gtable(ggplot_build(g))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.newpage()
grid.draw(gt)
This is as good as I can get without going into custom annotation grobs.
library(ggplot2)
library(grid)
df=data.frame(time=as.factor(rep(0.5:9.5,each=10)),
roi=rep(1:10,10),area=runif(100, 5.0, 7.5))
df$time=factor(df$time, levels=rev(levels(df$time)))
p1 <- ggplot(data=df, aes(x=factor(roi), y=time, fill = area)) +
theme_minimal() +coord_fixed(ratio=1) +
geom_tile(colour = NA, width = 1.5, height = 1)+
scale_fill_gradient(low="black",high="white") +
scale_x_discrete(breaks = c(4,6,8,10),
labels = paste0("Seg",1:4)) +
theme(axis.title.x = element_blank(),
axis.ticks.x = element_line(size =1),
axis.text.x = element_text(hjust=c(2,1.5,1.5,1.5)),
plot.margin = unit(c(2,0,2,0), "lines"))
See here if you want to look into drawing the axis labels and tick marks customwise.

Add same gradient to each rectangle in ggplot

I am trying to display color gradient in below created ggplot2. So with using following data and code
vector <- c(9, 10, 6, 5, 5)
Names <- c("Leadership", "Management\n", "Problem Solving",
"Decision Making\n", "Social Skills")
# add \n
Names[seq(2, length(Names), 2)] <- paste0("\n" ,Names[seq(2, length(Names), 2)])
# data.frame, including a grouping vector
d <- data.frame(Names, vector, group=c(rep("Intra-capacity", 3), rep("Inter-capacity", 2)))
# correct order
d$Names <- factor(d$Names, levels= unique(d$Names))
d$group_f = factor(d$group, levels=c('Intra-capacity','Inter-capacity'))
# plot the bars
p <- ggplot(d, aes(x= Names, y= vector, group= group, fill=vector, order=vector)) +
geom_bar(stat= "identity") +
theme_bw()+
scale_fill_gradient(low="white",high="blue")
# use facet_grid for the groups
#p + facet_grid(.~group_f, scales= "free_x", space= "free_x")
p+ theme(text = element_text(size=23),plot.background = element_rect(fill = "white"),
strip.background = element_rect(fill="Dodger Blue")) +
facet_grid(.~group_f, scales= "free_x", space= "free_x") + xlab("") +ylab("") +
theme(strip.text.x = element_text(size = 18, colour = "white" )) +
geom_text(size=10, aes(label=vector))
My output is this:
But now I would like to insert color gradient so each rectangle would look like picture below (my desired output):
I've also looked at this:
R: gradient fill for geom_rect in ggplot2
create an arrow with gradient color
http://www.computerworld.com/article/2935394/business-intelligence/my-ggplot2-cheat-sheet-search-by-task.html
Color Gradients With ggplot
Label minimum and maximum of scale fill gradient legend with text: ggplot2
How can I apply a gradient fill to a geom_rect object in ggplot2?
And also tried using:
scale_fill_gradient(low="white",high="blue") or
scale_fill_gradientn(colours = c("blue","white","red"),
values = c(0,5,10),
guide = "colorbar", limits=c(0,10))
But I am clearly doing something wrong.
I'm with #RomanLustrik here. However, if you can't use Excel (= prly much easier), maybe just adding a white rectangle with an alpha-gradient is already enough:
ggplot(d, aes(x= Names, y= vector, group= group,order=vector)) +
geom_bar(stat= "identity", fill="blue") +
theme_bw() +
scale_fill_gradient(low="white",high="blue") +
annotation_custom(
grid::rasterGrob(paste0("#FFFFFF", as.hexmode(1:255)),
width=unit(1,"npc"),
height = unit(1,"npc"),
interpolate = TRUE),
xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=5
) +
geom_text(aes(label=vector), color="white", y=2, size=12)

Resources