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")))
Related
I have two ggplots that I can created like this:
df1 = data.frame(x=1:10, y1=11:20, y2=21:30)
gg1 = ggplot(df1) + geom_point(aes(x=x, y=y1))
gg2 = ggplot(df1) + geom_point(aes(x=x, y=y2))
grid.arrange(gg1, gg2, top=textGrob("Here should be some space above",
gp=gpar(fontsize=18,
fontfamily="Times New Roman")))
Now the output looks like this:
One does not see it here as it is white on white, but I would like to create more space in the output-image above the title. And I'm not really sure on how to do it. Here is described on how to add space between the single plots Margins between plots in grid.arrange , but I did not manage to just add space above the header.
Making use of arrangeGrob you could add some margin on top of your header via a zeroGrob like so:
library(ggplot2)
library(gridExtra)
library(grid)
df1 = data.frame(x=1:10, y1=11:20, y2=21:30)
gg1 = ggplot(df1) + geom_point(aes(x=x, y=y1))
gg2 = ggplot(df1) + geom_point(aes(x=x, y=y2))
title <- textGrob("Here should be some space above",
gp=gpar(fontsize=18, fontfamily="Times New Roman"))
# Add a zeroGrob of height 2cm on top of the title
title <- arrangeGrob(zeroGrob(), title,
widths = unit(1, 'npc'),
heights = unit(c(2, 1), c('cm', 'npc')),
as.table = FALSE)
grid.arrange(gg1, gg2, top = title)
Can you live with another package?
library(patchwork)
plot_spacer()/ (gg1 + ggtitle("there is now space above")) / gg2 + plot_layout(heights = c(.5,1,1))
Or set the title margin in the first plot
gg1 = ggplot(df1) + geom_point(aes(x=x, y=y1)) +
ggtitle("there is now space above") +
theme(plot.title = element_text(margin = margin(t = 1, unit = "in")))
gg1 / gg2
I would like to display a set of parameters in the ggplot2 faceted plot format. Three of the parameters come from the same dataset and can be easily faceted. I'd now like to add a fourth plot into the grid, the dataset of which is a completely different length/value to the others (but still relevant to view together).
This is the best I have (terrible). Is there a way to exactly align the coordinates and theme? Thank you
library(ggplot2)
data(mtcars)
data(iris)
a_plot <- ggplot(mtcars, aes(mpg, disp))+
geom_line()+
facet_wrap(~cyl,nrow=2,scales='free')+
theme_bw()
b_plot<- ggplot(iris, aes(Sepal.Length,Petal.Length))+
geom_line()+
ggtitle('imposter')+
theme_bw()
vp <- viewport(width = 0.52, height = 0.5, x = 0.75, y = 0.25)
png("test.png")
print(a_plot)
print(b_plot, vp = vp)
dev.off()][1]][1]
One suggestion would be to handle this in the data and let the plot faceting work naturally. (I'm using dplyr here to combine the datasets, but it's only for convenience. Any mechanism that provides a single set of columns to plot on should work.)
library(dplyr)
library(ggplot2)
bind_rows(
transmute(mtcars, x=mpg , y=disp , z=as.character(cyl)),
transmute(iris, x=Sepal.Length, y=Petal.Length, z="imposter")
) %>%
ggplot(aes(x, y)) +
geom_line() +
facet_wrap(~ z, nrow = 2, scales = "free") +
theme_bw()
Use the parameter plot.margin and panel.spacing in the them to customize the size of the background you are plotting. And then modify the viewport to width so it matches your other 3 plots. You will probably have to try some times but it is achievable.
library(ggplot2)
library(grid)
a_plot <- ggplot(mtcars, aes(mpg, disp))+
geom_line()+
facet_wrap(~cyl,nrow=2,scales='free')+
theme_bw()+
theme(plot.margin = unit(c(0,0.3,0,0), "cm"),
panel.spacing= unit(1, "cm"))
b_plot<- ggplot(mtcars, aes(mpg,disp))+
geom_line()+
ggtitle('imposter')+
theme_bw()
vp <- viewport(width = 0.49, height = 0.5, x = 0.75, y = 0.25)
print(a_plot)
print(b_plot, vp = vp)
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
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)
If you look at the charts here! you can see there is a lot of white space above and below the legend. I wish to reduce the amount of space.
Example code:
library(ggplot2)
library(gridExtra)
library(reshape)
library(plyr)
library(scales)
theme_set(theme_bw())
rows <- 1:nrow(faithful)
data <- cbind(faithful, rows)
molten <- melt(data, id.vars='rows', measure.vars=c('eruptions', 'waiting'))
p <- ggplot() +
geom_line(data=molten,
mapping=aes(x=rows, y=value, group=variable, colour=variable), size=0.8) +
scale_colour_manual(values=c('red','blue')) +
opts(title='Title') +
xlab(NULL) + ylab('Meaningless Numbers') +
opts(
legend.position='bottom',
legend.direction='horizontal',
legend.title=theme_blank(),
legend.key=theme_blank(),
legend.text=theme_text(size=9),
legend.margin = unit(0, "line"),
legend.key.height=unit(0.6,"line"),
legend.background = theme_rect(colour='white', size=0)
)
ggsave(p, width=8, height=4, filename='crap.png', dpi=125)
To remove the margins of the legend (negative values reduce the white space even more):
p + theme(legend.margin=margin(t=0, r=0, b=0, l=0, unit="cm"))
p + theme(legend.margin=margin(t=0, r=0, b=-0.5, l=0, unit="cm"))
You can also remove the lower part of the plot margin by specifying negative numbers (but make sure that you don't cut off your legend):
p + theme(plot.margin = unit(x = c(0, 0, -0.2, 0), units = "cm"))
Illustrations: ggplot2, legend on top and margin
Here are two additional options that allow you to shrink the space surround the legend:
p + theme(
legend.key.height=unit(0, "cm"),
plot.margin = unit(c(1,0.5,0,0.5), "lines")
)
The option plot.margin describes how much space there is around the plot itself. The third argument describes the amount of space below the plot. Setting that to zero helps.