ggplot no grid visual on top of imported image - r

I'm trying to plot some data on top of an imported image using ggplot2. However I can not get a visual grid in the plot..
Here is a simplified example to illustrate my issue:
library(ggplot2)
library(scales)
library(jpeg)
library(scales)
library(grid)
#picture from internet
myurl <- "http://upload.wikimedia.org/wikipedia/commons/9/95/Apollonian_spheres.jpg"
z <- tempfile()
download.file(myurl,z,mode="wb")
pic <- readJPEG(z)
file.remove(z) # cleanup
x <- sample(1:10, replace=T, 10)
y <- c("a","b","c","d","e","f","g","h","i", "j")
df <- data.frame(y,x)
p <-ggplot(df, aes(y, x, fill=y)) +
annotation_custom(rasterGrob(pic, width=unit(1,"npc"), height=unit(1,"npc")),
-Inf, Inf, -Inf, Inf) +
geom_bar(stat = "identity", fill="darkorange",width=0.8, alpha=0.75 )+
#geom_text(aes(label=data2$Attributes), vjust=1.5,colour="black")
coord_flip() + ggtitle("Something")+ theme_classic() +
labs(y = "yyy", x = "xxx") + guides(fill = guide_legend(reverse=TRUE))+
theme(axis.text.y = element_blank()) + theme(plot.title = element_text(size=20))+
theme(axis.title.x = element_text(size = 16))+ theme(axis.title.y = element_text(size = 16))+
theme(legend.text = element_text( size = 14)) + theme(legend.title = element_text( size = 16))+
theme(panel.grid.major = element_line(colour = "white", linetype = "dotted"))
p
#without picture works fine
p <-ggplot(df, aes(y, x, fill=y)) +
geom_bar(stat = "identity", fill="darkorange",width=0.8, alpha=0.75 )+
#geom_text(aes(label=data2$Attributes), vjust=1.5,colour="black")
coord_flip() + ggtitle("Something")+ theme_classic() +
labs(y = "yyy", x = "xxx") + guides(fill = guide_legend(reverse=TRUE))+
theme(axis.text.y = element_blank()) + theme(plot.title = element_text(size=20))+
theme(axis.title.x = element_text(size = 16))+ theme(axis.title.y = element_text(size = 16))+
theme(legend.text = element_text( size = 14)) + theme(legend.title = element_text( size = 16))+
theme(panel.grid.major = element_line(colour = "black", linetype = "dotted"))
p
Any ideas?

Related

Having trouble aligning histogram and density plots in ggplot2 with cowplot

Only the stripped down density plot appears in the output:
library(ggplot2)
library(cowplot)
raises <- attitude$raises
df <- data.frame(raises)
ph <- ggplot(df, aes(x = raises)) +
geom_histogram(binwidth = 1, color = "black", fill = "light grey") +
scale_x_continuous(breaks = seq(40, 90, by = 10)) +
ylim(0,3) +
theme_classic()
pd <- ggplot(df, aes(x = raises)) +
geom_density() +
scale_x_continuous(breaks = seq(40, 90, by = 10)) +
scale_y_continuous(expand = expansion(mult = c(0, 0.1)), position = "right") +
theme_classic() +
theme(axis.line.x = element_blank(),
axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank())
alpl <- align_plots(ph, pd, align = "hv", axis = "tblr")
ggdraw(alpl[[1]]) + draw_plot(alpl[[2]])
I would like to overlay them so that you can see the histogram with the frequency as well as the density.
You have an opaque plot background and panel background in your density plot which you need to remove in theme. Obviously, I don't have your data, but the following code gives you the idea:
library(ggplot2)
library(cowplot)
set.seed(1)
df <- data.frame(raises = c(rnorm(100, 65, 10)))
ph <- ggplot(df, aes(x = raises)) +
geom_histogram(binwidth = 1, color = "black", fill = "light grey") +
scale_x_continuous(breaks = seq(40, 90, by = 10), limits = c(40, 90)) +
ylim(0,3) +
theme_classic()
pd <- ggplot(df, aes(x = raises)) +
geom_density() +
scale_x_continuous(breaks = seq(40, 90, by = 10), limits = c(40, 90)) +
scale_y_continuous(expand = expansion(mult = c(0, 0.1)), position = "right") +
theme_classic() +
theme(axis.line.x = element_blank(),
axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
plot.background = element_blank(),
panel.background = element_blank())
alpl <- align_plots(ph, pd, align = "hv", axis = "tblr")
ggdraw(alpl[[1]]) + draw_plot(alpl[[2]])

Label individual plots in facet_grid

I am trying to finish this graph, and what I need is to add the R-squared to each graph individually.
However, the labels are superimposed on each graph.
I used p + geom_text and p + geom_label without positive results.
Trajectories$date<-as.POSIXct(Trajectories$date,"%Y-%m-%d",tz = "UTC")
# Reorder names in a new variable
Trajectories$variable_f = factor(Trajectories$variable,
levels=c("canopy_cover", "Leaf_litter", "Chla", "Shrimps", "macroinvertebrates"))
levels(Trajectories$variable_f) <-
c("textstyle('Canopy openness')",
"textstyle('Leaf litter')",
"textstyle('Chlorophyll-')*italic('a')",
"textstyle('Shrimps')",
"atop(NA,atop(textstyle('Macroinvertebrate'),textstyle('density')))")
# Changes names in Facet_grid ---- es una manera buena, pero no la voy a usar --- Habria que labeller(variable_f = variable_f
#variable_f <- c("Canopy openness", "Leaf litter", "Chlorophyll-a","Shrimps","Macroinvertebrates")
#names(variable_f) <- c("canopy_cover", "Leaf_litter", "Chla", "Shrimps", "macroinvertebrates")
streams <- c("Prieta A", "Prieta B")
names(streams) <- c("QPA", "QPB")
# General graph -----------------------------------------------------------
p<- ggplot(Trajectories, aes(date,value)) +
geom_point(shape = 21, fill = "#bdd7e7", color = "#2171b5", size = 3) +
geom_smooth(se = T, size=1.7, color= "gray20", method = "gam", formula = y ~s(x)) +
geom_hline(yintercept = 0, color="gray20") +
xlab('Year') + ylab("Change in magnitude") +
theme(axis.title.x = element_text(size = 14, angle = 0)) + # axis x
theme(axis.title.y = element_text(size = 14, angle = 90)) + # axis 7
theme(axis.text.x=element_text(angle=0, size=10, vjust=0.5, color="black")) + #subaxis x
theme(axis.text.y=element_text(angle=0, size=10, vjust=0.5, color="black")) + #subaxis y
ylim(-3,3) +
theme(legend.position="none")+
theme(panel.grid.major = element_line(colour = "gray95"), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black")) +
theme(panel.border = element_rect(colour = "black", fill=NA, size=0.5)) +
facet_grid(vars(stream), vars(variable_f),
labeller = labeller(variable_f = label_parsed, stream = streams)) +
theme(
strip.text.x = element_text(size = 10, color = "black"),
strip.text.y = element_text(size = 10, color = "black"),
strip.placement = "outside") +
theme(strip.background=element_rect(color= "black", fill="gray85")) +
theme(strip.text.x = element_text(margin = margin(0.001,0,0.001,0, "cm"))) +
geom_vline(aes(xintercept=as.POSIXct("2017-09-21")), # Hurricane Maria
col= "red",linetype=4, alpha=0.9) +
geom_vline(aes(xintercept=as.POSIXct("2017-09-6")), # Hurricane Irma
col= "blue",linetype=4, alpha=0.9)
p
I tried to build a data frame with the labels. But it doesn't work, and it overlaps the labels.
labels <- data.frame(variable =c("canopy_cover","Leaf_litter","Chla","Shrimps","macroinvertebrates",
"canopy_cover","Leaf_litter","Chla","Shrimps","macroinvertebrates"),
label=c("R1","R2","R3","R4","R5","R6","R7","R8","R9","R10"),
stream= c("QPA","QPA","QPA","QPA","QPA",
"QPB","QPB","QPB","QPB","QPB"))
labels
p + geom_text(
size = 5,
data = labels,
mapping = aes(x = as.POSIXct("2017-09-6"), y = Inf, label = label),
hjust = 1.05,
vjust = 1.5
)
Thanks in advance

ggplot2: missing legend and how to add?

I want to plot a bar and line chart from a dataframe. Code below,
library("ggplot2")
numb <- c(1,2,3,4,5,6,7,8,9)
mydist <- c(53.846154,15.384615,15.384615,7.692308,7.692308,0,0,0,0)
basedist <- c(30.103,17.609126,12.493874,9.691001,7.918125,6.694679,5.799195,5.115252,4.575749)
df <- data.frame(numb, mydist, basedist)
ggplot(data=df,aes(x=numb)) +
geom_bar(stat="identity", aes(y=mydist), colour="green", fill="green") +
geom_line(aes(y=basedist,group=1, colour="base distribution")) +
geom_point(aes(y=basedist), colour="red") +
ggtitle("My Chart") +
labs(x="numb", y="percentage") +
scale_x_discrete(limits=c("1","2","3","4","5","6","7","8","9")) +
scale_y_continuous(breaks=seq(0,100,10)) +
theme(axis.title.x = element_text(size=10, colour ="#666666")) +
theme(axis.title.y = element_text(size=10, color="#666666")) +
theme(plot.title = element_text(size=16, face="bold", hjust=0, color="#666666")) +
theme(axis.text = element_text(size=12)) +
theme(legend.title = element_text(colour="white", size = 16, face='bold'))
Result is not I wanted because there is no legend for the bars
I reproduced the chart I need with the same data set in Excel below,
What do I need to change in my code to get the chart I need?
Thanks,
Lobbie
Here is a brief example. In general, I would recommend you reformat ggplot() assignment to make debugging easier. i.e. gp <- gp +
gp <- ggplot(data=df, aes(x=numb))
gp <- gp + geom_bar( aes(y = mydist, fill = "green"), stat="identity", color="green")
gp <- gp + geom_line( aes( y = basedist, group = 1, colour = "base distribution"))
gp <- gp + scale_fill_manual(values = "green", labels = "my distribution")
gp <- gp + geom_point(aes(y=basedist), colour="red")
gp <- gp + ggtitle("My Chart")
gp <- gp + labs(x="numb", y="percentage")
gp <- gp + scale_x_discrete(limits=c("1","2","3","4","5","6","7","8","9"))
gp <- gp + scale_y_continuous(breaks=seq(0,100,10))
gp <- gp + theme(axis.title.x = element_text(size=10, colour ="#666666"))
gp <- gp + theme(axis.title.y = element_text(size=10, color="#666666"))
gp <- gp + theme(plot.title = element_text(size=16, face="bold", hjust=0, color="#666666"))
gp <- gp + theme(axis.text = element_text(size=12))
gp <- gp + theme(legend.title = element_text(colour="white", size = 16, face='bold'))
gp <- gp + theme(legend.key = element_blank(), legend.title=element_blank(), legend.box ="vertical")
gp
Without changing much of the original code, you only need to put your fill into aes mapping, then add the scale to set the colour values and labels:
ggplot(data=df,aes(x=numb)) +
geom_bar(stat="identity", aes(y=mydist, fill="green"), colour="green") +
geom_line(aes(y=basedist,group=1, colour="base distribution")) +
geom_point(aes(y=basedist), colour="red") +
ggtitle("My Chart") +
labs(x="numb", y="percentage") +
scale_x_discrete(limits=c("1","2","3","4","5","6","7","8","9")) +
scale_y_continuous(breaks=seq(0,100,10)) +
scale_fill_manual(values = "green", labels = "my distribution") +
theme(axis.title.x = element_text(size=10, colour ="#666666")) +
theme(axis.title.y = element_text(size=10, color="#666666")) +
theme(plot.title = element_text(size=16, face="bold", hjust=0, color="#666666")) +
theme(axis.text = element_text(size=12)) +
theme(legend.title = element_text(colour="white", size = 16, face='bold'))

import image,lay filter on top and then plot data

I would like to plot data on top of an imported picture in R. I would also like to lay a filtering layer on the image if possible, like controlling transparency color in ggplot2 with the alpha value:
here is an example to work on:
library(ggplot2)
library(scales)
library(jpeg)
library(scales)
library(grid)
#picture from internet
myurl <- "http://upload.wikimedia.org/wikipedia/commons/9/95/Apollonian_spheres.jpg"
z <- tempfile()
download.file(myurl,z,mode="wb")
pic <- readJPEG(z)
file.remove(z) # cleanup
x <- sample(1:10, replace=T, 10)
y <- c("a","b","c","d","e","f","g","h","i", "j")
df <- data.frame(y,x)
p <-ggplot(df, aes(y, x, fill=y)) +
annotation_custom(rasterGrob(pic, width=unit(1,"npc"), height=unit(1,"npc")),
-Inf, Inf, -Inf, Inf) +
geom_bar(stat = "identity", fill="red",width=0.8, alpha=0.75 )+
#geom_text(aes(label=data2$Attributes), vjust=1.5,colour="black")
ggtitle("Something")+ theme_classic() +
labs(y = "yyy", x = "xxx") + guides(fill = guide_legend(reverse=TRUE))+
theme(axis.text.y = element_blank()) + theme(plot.title = element_text(size=20))+
theme(axis.title.x = element_text(size = 16))+ theme(axis.title.y = element_text(size = 16))+
theme(legend.text = element_text( size = 14)) + theme(legend.title = element_text( size = 16))+
theme(panel.grid.major = element_line(colour = "white", linetype = "dotted"))
p
This results in a picture:
any ideas?

R stacked bar graph plotting geom_text

I'm trying to plot a stacked bar graph in R using ggplot. I also want to include percentage in each piece of bars for that piece. I tried to follow the posts 1, 2, 3 but the values are not exactly in their respective blocks. My data is a file in dropbox.
My code is as follows:
f<-read.table("Input.txt", sep="\t", header=TRUE)
ggplot(data=f, aes(x=Form, y=Percentage, fill=Position)) +
geom_bar(stat="identity", colour="black") +
geom_text(position="stack", aes(x=Form, y=Percentage, ymax=Percentage, label=Percentage, hjust=0.5)) +
facet_grid(Sample_name ~ Sample_type, scales="free", space="free") +
opts(title = "Input_profile",
axis.text.x = theme_text(angle = 90, hjust = 1, size = 8, colour = "grey50"),
plot.title = theme_text(face="bold", size=11),
axis.title.x = theme_text(face="bold", size=9),
axis.title.y = theme_text(face="bold", size=9, angle=90),
panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank()) +
scale_fill_hue(c=45, l=80)
ggsave("Output.pdf")
The output is-
Any help is greatly appreciated.
Thank you for your help and time!
I think you're using an older version of ggplot2. Because with your code modified for ggplot2 v 0.9.3, I get this:
p <- ggplot(data = df, aes(x = Form, y = Percentage, fill = Position))
p <- p + geom_bar(stat = "identity", colour = "black")
p <- p + geom_text(position = "stack", aes(x = Form, y = Percentage, ymax = Percentage, label = Percentage, hjust = 0.5))
p <- p + facet_grid(Sample_name ~ Sample_type, scales="free", space="free")
p <- p + theme(plot.title = element_text("Input_profile"),
axis.text.x = element_text(angle = 90, hjust = 1, size = 8, colour = "grey50"),
plot.title = element_text(face="bold", size=11),
axis.title.x = element_text(face="bold", size=9),
axis.title.y = element_text(face="bold", size=9, angle=90),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
p <- p + scale_fill_hue(c=45, l=80)
p
You see that the text objects are normally placed properly. There are places where the bars are just too short so that the numbers overlap. You can also play with the size parameter.
To rectify that, you could do something like this to add up the numbers by yourself.
df <- ddply(df, .(Form, Sample_type, Sample_name), transform,
cum.perc = Reduce('+', list(Percentage/2,cumsum(c(0,head(Percentage,-1))))))
p <- ggplot(data = df, aes(x = Form, y = Percentage, fill = Position))
p <- p + geom_bar(stat = "identity", colour = "black")
p <- p + geom_text(aes(x = Form, y = cum.perc, ymax = cum.perc, label = Percentage, hjust = 0.5), size=2.7)
p <- p + facet_grid(Sample_name ~ Sample_type, scales="free", space="free")
p <- p + theme(plot.title = element_text("Input_profile"),
axis.text.x = element_text(angle = 90, hjust = 1, size = 8, colour = "grey50"),
plot.title = element_text(face="bold", size=11),
axis.title.x = element_text(face="bold", size=9),
axis.title.y = element_text(face="bold", size=9, angle=90),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
p <- p + scale_fill_hue(c=45, l=80)
p
This gives:
Here a solution using barchart from lattice.
library(latticeExtra)
barchart(Percentage~Form|Sample_type*Sample_name,data=dat,
groups =Position,stack=T,
panel=function(...){
panel.barchart(...)
ll <- list(...)
keep <- !is.na(ll$groups[ll$subscripts])
x <- as.numeric(ll$x[keep])
y <- as.numeric(ll$y[keep])
groups <- as.numeric(factor(ll$groups)[ll$subscripts[keep]])
for (i in unique(x)) {
ok <- x == i
ord <- sort.list(groups[ok])
pos <- y[ok][ord] > 0
nok <- sum(pos, na.rm = TRUE)
h <- y[ok][ord][pos]
panel.text(x = rep(i, nok),y = cumsum(h)-0.5*h,
label = h,cex=1.5)
}
},
auto.key = list(columns = 5),
par.settings = ggplot2like(n = 5),
lattice.options = ggplot2like.opts())

Resources