I'm doing an arrangement of 2x2 plots. The plots share the same axis, so I want to put them together, e.g.
This code:
library(ggplot2)
library(cowplot)
Value <- seq(0,1000, by = 1000/10)
Index <- 0:10
DF <- data.frame(Index, Value)
plot <- ggplot(DF, aes(x = Index, y = Value)) +
geom_line(linetype = 2) +
theme(aspect.ratio = 0.5)
plot_grid(plot, plot, plot, plot, align = "hv", ncol = 2)
produces
But I'd like something like:
How can I achieve a similar result?
I think this is a case for the ggarrange() function from the egg package. Doing this with plot_grid() would require endless fiddling and isn't worth it.
(The technical reason is that plot_grid() keeps the total area for each plot in the grid constant, but if some plots have an x axis and others don’t then they take up different areas. One could try to circumvent this by using the rel_heights argument but there’s no good way to calculate the correct values for rel_heights, so it would be trial and error. By contrast, ggarrange() separately looks at the plot panel and the surrounding elements and makes sure the plot panels have the same size.)
Here is the code using ggarrange():
Value <- seq(0,1000, by = 1000/10)
Index <- 0:10
DF <- data.frame(Index, Value)
pbase <- ggplot(DF, aes(x = Index, y = Value)) +
geom_line(linetype = 2) +
theme_bw()
ptopleft <- pbase +
scale_x_continuous(position = "top") +
theme(plot.margin = margin(5.5, 0, 0, 5.5),
axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank())
ptopright <- pbase +
scale_y_continuous(position = "right") +
scale_x_continuous(position = "top") +
theme(plot.margin = margin(5.5, 5.5, 0, 0),
axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank())
pbottomleft <- pbase +
theme(plot.margin = margin(0, 0, 5.5, 5.5))
pbottomright <- pbase +
scale_y_continuous(position = "right") +
theme(plot.margin = margin(0, 5.5, 5.5, 0))
library(egg)
ggarrange(ptopleft, ptopright,
pbottomleft, pbottomright,
ncol = 2)
Two comments:
To remove every last bit of space below the plot panel on the top plots, we need to move the x axis to the top, even though we're not showing it. This is a strange limitation of the theming mechanism. We can't fully get rid of just one axis.
I'm not a big fan of shared axis titles, as in your example. I think each axis should have a title. If you want shared axis titles, why not use the faceting mechanism?
You can set subtle plot.margin each plot, then grid.arrange and add labs.
library(ggplot2)
library(grid)
library(gridExtra)
Value <- seq(0,1000, by = 1000/10)
Index <- 0:10
DF <- data.frame(Index, Value)
plot1 <- ggplot(DF, aes(x = Index, y = Value)) +
geom_line(linetype = 2) +
theme_minimal() +
theme(aspect.ratio = 0.5,
panel.border = element_rect(fill = NA),
axis.text.x = element_blank(),
axis.title = element_blank(),
axis.ticks = element_blank(),
plot.margin = unit(c(5.5, 5.8, -50, 5.5), "pt"))
plot2 <- ggplot(DF, aes(x = Index, y = Value)) +
geom_line(linetype = 2) +
theme_minimal() +
theme(aspect.ratio = 0.5,
panel.border = element_rect(fill = NA),
axis.text.x = element_blank(),
axis.title = element_blank(),
axis.ticks = element_blank(),
plot.margin = unit(c(5.5, 5.5, -50, 5.5), "pt")) +
scale_y_continuous(position = "right")
plot3 <- ggplot(DF, aes(x = Index, y = Value)) +
geom_line(linetype = 2) +
theme_minimal() +
theme(aspect.ratio = 0.5,
panel.border = element_rect(fill = NA),
axis.title = element_blank(),
axis.ticks = element_blank(),
plot.margin = unit(c(-50, 5.8, -50, 5.5), "pt"))
plot4 <- ggplot(DF, aes(x = Index, y = Value)) +
geom_line(linetype = 2) +
theme_minimal() +
theme(aspect.ratio = 0.5,
panel.border = element_rect(fill = NA),
axis.title = element_blank(),
axis.ticks = element_blank(),
plot.margin = unit(c(-50, 5.5, -50, 5.5), "pt")) +
scale_y_continuous(position = "right")
grid.arrange(grobs = list(plot1, plot2, plot3, plot4), ncol = 2, bottom = 'Index', left = 'Value', right = 'Value')
final plot
Related
I have the following dummy data and plots:
library(ggplot2)
library(patchwork)
test_data <- data.frame(sample = c("sample1_long_label","sample2","sam3","sample4_long_labels_are_annoying"),
var1 = c(20,24,19,21),
var2 = c(4000, 3890, 4020, 3760))
p1 <- ggplot(test_data, aes(var1, sample)) +
geom_col() +
scale_x_reverse() +
theme(axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
axis.title.y = element_blank())
p2 <- ggplot(test_data, aes(var2, sample)) +
geom_col() +
theme(axis.title.y = element_blank(),
axis.ticks.y = element_blank())
p1 + p2
This creates a plot that looks like this:
Now, the y-axis labels are right-aligned to the right plot (they have been removed in the left plot). I would like the y-axis labels to be center-aligned between the two plots. Is this possible? If not, any other method that will create a similar plot is welcome.
Edit: I forgot to mention that the labels may be of different lengths, and have adjusted the test data. Is it possible to make the whole label visible in the center while center-adjusting the text?
I think it might be easiest to control the spacing through the y-axis text margin, and discard any other margins or spacing. To do this:
Set the right margin of the left plot to 0
Set the left margin of the right plot to 0
Set the tick length of the right plot to 0. Even though these are blank, still space is reserved for them.
Set the right and left margins of the axis text of the right plot.
In the code below, 5.5 points is the default margin space, but feel free to adjust that to personal taste.
library(ggplot2)
library(patchwork)
test_data <- data.frame(sample = c("sample1","sample2","sample3","sample4"),
var1 = c(20,24,19,21),
var2 = c(4000, 3890, 4020, 3760))
p1 <- ggplot(test_data, aes(var1, sample)) +
geom_col() +
scale_x_reverse() +
theme(axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
axis.title.y = element_blank(),
plot.margin = margin(5.5, 0, 5.5, 5.5))
p2 <- ggplot(test_data, aes(var2, sample)) +
geom_col() +
theme(axis.title.y = element_blank(),
axis.ticks.y = element_blank(),
axis.ticks.length = unit(0, "pt"),
plot.margin = margin(5.5, 5.5, 5.5, 0),
axis.text.y.left = element_text(margin = margin(0, 5.5, 0, 5.5)))
p1 + p2
Created on 2022-01-31 by the reprex package (v2.0.1)
EDIT: To center align labels with various lengths, you can use hjust as per usual: axis.text.y.left = element_text(margin = margin(0, 5.5, 0, 5.5), hjust = 0.5).
A second option would be to add the axis labels via a third plot:
library(ggplot2)
library(patchwork)
test_data <- data.frame(sample = c("sample1","sample2","sample3","sample4"),
var1 = c(20,24,19,21),
var2 = c(4000, 3890, 4020, 3760))
p1 <- ggplot(test_data, aes(var1, sample)) +
geom_col() +
scale_x_reverse() +
theme(axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
axis.title.y = element_blank())
p2 <- ggplot(test_data, aes(var2, sample)) +
geom_col() +
theme(axis.text.y = element_blank(),
axis.title.y = element_blank(),
axis.ticks.y = element_blank())
p3 <- ggplot(test_data, aes(1, sample)) +
geom_text(aes(label = sample)) +
scale_x_reverse() +
theme_void()
p1 + p3 + p2 +
plot_layout(widths = c(4, 1, 4))
I'm trying to plot a liine on the x axis which is basically a bunch of zeros and ones. Ones are green and zeros are red. When I try to do that, the color_scale_gradient of the ggplot basically colors on top of the line.
It looks like this
Where the line should be colored as follows:
colorbar is a vector of zeros and ones.
p <- ggplot(data1,aes(newx,newy, group = 1, colour=newy))+
geom_line(size=1.5, show.legend = FALSE)+
scale_colour_gradient(low="red2", high="green3") +
geom_line(data = colorFrame, aes(as.numeric(x)-5,as.numeric(ys), color = colorbar),size=3, show.legend = FALSE)+
xlim(0,1300)
p <- p +
theme(panel.background = element_blank(), axis.ticks.x = element_blank(),
axis.text.x = element_blank(), axis.line.y = element_line(colour = 'black'),
axis.ticks.y.left = element_line(colour = 'black')) +
scale_y_continuous(breaks = seq(0, 12, 1), limits = c(-1, 12), expand = c(0,0))
One solution would be to create two subplots and stitch them together. I use cowplot and theme_void here, but really the second plot below could look however you want it to.
p1 <- ggplot(df, aes(x,y, group = 1, colour=y)) +
geom_line(size=1.5, show.legend = FALSE) +
scale_colour_gradient(low="red2", high="green3") +
theme(panel.background = element_blank(),
axis.ticks.x = element_blank(),
axis.text.x = element_blank(),
axis.line.y = element_line(colour = 'black'),
axis.ticks.y.left = element_line(colour = 'black')) +
scale_y_continuous(breaks = seq(0, 12, 1), limits = c(-1, 12), expand = c(0,0)) +
labs(x = NULL)
p2 <- ggplot(df, aes(x, y = 0, colour=z)) +
geom_line(size=1.5, show.legend = FALSE) +
scale_colour_gradient(low="red2", high="green3") +
theme_void()
cowplot::plot_grid(p1, p2,
ncol = 1,
rel_heights = c(1, .05),
align = 'v')
Data
df <- data.frame(x = 1:50,
y = runif(50, 0, 12),
z = sample(c(0,1), 50, replace = TRUE))
I am creating faceted box plots that are grouped by a variable. Instead of having the x-axis text be the factors for the x-axis variable I'd like the x-axis text to be the grouping variable.
However, I don't just want to use the grouping variable as my x-axis variable because I'd like the boxplots to cluster. Its hard to explain well. But I think its clear from the code and comments below.
Let me know if you have any suggestions or can help and thanks in advance!
library(ggplot2)
library(scales)
ln_clr <- "black"
bk_clr <- "white"
set.seed(1)
# Creates variables for a dataset
donor = rep(paste0("Donor",1:3), each=40)
machine = sample(rep(rep(paste0("Machine",1:4), each=1),30))
gene = rep(paste0("Gene",LETTERS[1:5]), each=24)
value = rnorm(24*5, mean=rep(c(0.5,10,1000,25000,8000), each=24),
sd=rep(c(0.5,8,900,9000,3000), each=24))
# Makes all values positive
for(m in 1:length(value)){
if(value[m]<0){
value[m] <- sqrt(value[m]*value[m])
}
}
# Creates a data frame from variables
df = data.frame(donor, machine, gene, value)
# Adds a clone variable
clns <- LETTERS[1:4]
k=1
for(i in 1:nrow(df)/4){
for(j in 1:length(clns)){
df$clone[k] <- paste(df$donor[k],clns[j],sep="")
k = k+1
}
}
df$clone <- as.factor(df$clone)
#*************************************************************************************************************************************
# Creates the facet of the machine but what I want on the x-axis is clone, not donor.
# However, if I set x to clone it doesn't group the boxplots and its harder to read
# the graph.
bp1 <- ggplot(df, aes(x=donor, y=value, group=clone)) +
stat_boxplot(geom ='errorbar', position = position_dodge(width = .83),
width = 0.25, size = 0.7, coef = 1) +
geom_boxplot(coef=1, outlier.shape = NA, position = position_dodge(width = .83),
lwd = 0.3, alpha = 1, colour = ln_clr) +
geom_point(position = position_dodge(width = 0.83), size = 1.8, alpha = 0.9,
mapping=aes(group=clone)) +
facet_wrap(~ machine, ncol=2, scales="free_x")
bp1 + scale_y_log10(expand = c(0, 0)) +
theme(axis.text.x= element_text(size=rel(1), colour = "black", angle=45, hjust=1),
strip.background = element_rect(colour = ln_clr, fill = bk_clr, size = 1))
# Creates the facet of the Donor and clusters the clones but doesn't facet the
# machine. This could be okay if I could put spaces in between the different
# machine values but not the donors and could remove the donor facet labels, and
# only have the machine values show up once.
bp2 <- ggplot(df, aes(x=clone, y=value)) +
stat_boxplot(geom ='errorbar', position = position_dodge(width = .83),
width = 0.25, size = 0.7, coef = 1) +
geom_boxplot(coef=1, outlier.shape = NA, position = position_dodge(width = .83),
lwd = 0.3, alpha = 1, colour = ln_clr) +
geom_point(position = position_dodge(width = 0.83), size = 1.8, alpha = 0.9) +
facet_wrap(machine ~ donor, scales="free_x", ncol=6)
bp2 + scale_y_log10(expand = c(0, 0)) +
theme(axis.text.x= element_text(size=rel(1), colour = "black", angle=45, hjust=1),
strip.background = element_rect(colour = ln_clr, fill = bk_clr, size = 1),
panel.spacing = unit(0, "lines"))
Below is an example comparing what I'd like in an ideal world (Top two facets) as compared to what I'm getting (bottom two facets).
I'm not sure I understand exactly what you're trying to do, so let me know if this is on the right track:
library(dplyr)
pd = position_dodge(width=0.83)
ggplot(df %>% mutate(clone=gsub("Donor[1-3]","",clone),
donor=gsub("Donor", "", donor)),
aes(x=clone, y=value, color=donor, group=interaction(clone,donor))) +
geom_boxplot(coef=1, outlier.shape=NA, position=pd, lwd=0.3) +
geom_point(position=pd, size=1.8, alpha=0.9) +
facet_wrap(~ machine, ncol=2, scales="free_x") +
scale_y_log10(expand = c(0.02, 0)) +
theme(strip.background=element_rect(colour=ln_clr, fill=bk_clr, size=1))
How about this:
ggplot(df, aes(x=clone, y=value, group=interaction(clone,donor))) +
geom_boxplot(coef=1, outlier.shape=NA, lwd=0.3) +
geom_point(size=1.8, alpha=0.9) +
facet_wrap(~ machine, ncol=2, scales="free_x") +
scale_y_log10(expand = c(0.02, 0)) +
theme(axis.text.x= element_text(size=rel(1), colour = "black", angle=45, hjust=1),
strip.background=element_rect(colour=ln_clr, fill=bk_clr, size=1))
I found a work around for this problem but its not very elegant. I'd be super happy if some one came up with a better solution. Using the code to create a function for a "multiplot" found here and adding the code below I was able to do what I wanted. However, This is a slightly wonky solution in that I can't really format my titles with boxes around them and there are still two "clone" titles on the x axis that I can't replace easily with a single x-axis title. Also, had I of had many "machines" in my example this solution would have been painful to scale. All-in-all not ideal but passible for what I need. Special thanks to Eipi10 for their help, I appreciate it.
# Creates a multi-plot function for use in the graphs below
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
library(grid)
# Make a list from the ... arguments and plotlist
plots <- c(list(...), plotlist)
numPlots = length(plots)
# If layout is NULL, then use 'cols' to determine layout
if (is.null(layout)) {
# Make the panel
# ncol: Number of columns of plots
# nrow: Number of rows needed, calculated from # of cols
layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
ncol = cols, nrow = ceiling(numPlots/cols))
}
if (numPlots==1) {
print(plots[[1]])
} else {
# Set up the page
grid.newpage()
pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
# Make each plot, in the correct location
for (i in 1:numPlots) {
# Get the i,j matrix positions of the regions that contain this subplot
matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
layout.pos.col = matchidx$col))
}
}
}
# Call multiplot function after storing each of the below plots as variables
ln_clr <- "black"
bk_clr <- "white"
bp3 <- ggplot(df[df$machine=="Machine1",], aes(x=clone, y=value)) +
geom_boxplot(coef=1, outlier.shape=NA, lwd=0.3) +
geom_point(size=1.8, alpha=0.9) +
ggtitle("Machine 1") +
expand_limits(y=c(0.001,10^5)) +
facet_wrap(~ donor, nrow=1, scales="free_x") + scale_y_log10(expand = c(0, 0)) +
theme(axis.text.x= element_text(size=rel(1), color = ln_clr, angle=45, hjust=1),
panel.spacing = unit(0.25, "lines"), axis.title.x= element_blank(),
plot.title = element_text(hjust=0.5),
strip.text.x = element_text(size=rel(1), face="bold", colour = ln_clr),
strip.background = element_rect(colour = ln_clr, fill = bk_clr, size = 1),
axis.line.x= element_line(size = 1.25, colour = ln_clr),
axis.line.y= element_line(size = 1.25, colour = ln_clr),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(fill = bk_clr),
panel.border = element_blank(),
plot.background = element_rect(fill = bk_clr))
bp4 <- ggplot(df[df$machine=="Machine2",], aes(x=clone, y=value)) +
geom_boxplot(coef=1, outlier.shape=NA, lwd=0.3) +
geom_point(size=1.8, alpha=0.9) +
ggtitle("Machine 2") +
expand_limits(y=c(0.001,10^5)) +
facet_wrap(~ donor, nrow=1, scales="free_x") + scale_y_log10(expand = c(0, 0)) +
theme(axis.text.x= element_text(size=rel(1), colour = ln_clr, angle=45, hjust=1),
panel.spacing = unit(0.25, "lines"), plot.title = element_text(hjust=0.5),
strip.text.x = element_text(size=rel(1), face="bold", colour = ln_clr),
strip.background = element_rect(colour = ln_clr, fill = bk_clr, size = 1),
axis.line.x= element_line(size = 1.25, colour = ln_clr),
axis.line.y= element_line(size = 1.25, colour = ln_clr),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(fill = bk_clr),
panel.border = element_blank(),
plot.background = element_rect(fill = bk_clr))
bp5 <- ggplot(df[df$machine=="Machine3",], aes(x=clone, y=value)) +
geom_boxplot(coef=1, outlier.shape=NA, lwd=0.3) +
geom_point(size=1.8, alpha=0.9) +
ggtitle("Machine 3") +
expand_limits(y=c(0.001,10^5)) +
facet_wrap(~ donor, nrow=1, scales="free_x") + scale_y_log10(expand = c(0, 0)) +
theme(panel.spacing = unit(0.25, "lines"), axis.title.y= element_blank(),
axis.title.x= element_blank(),axis.line.y= element_blank(),
axis.text.y=element_blank(),
axis.text.x= element_text(size=rel(1), colour = ln_clr, angle=45, hjust=1),
axis.ticks.y=element_blank(), plot.title = element_text(hjust=0.5),
strip.text.x = element_text(size=rel(1), face="bold", colour = ln_clr),
strip.background = element_rect(colour = ln_clr, fill = bk_clr, size = 1),
axis.line.x= element_line(size = 1.25, colour = ln_clr),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(fill = bk_clr),
panel.border = element_blank(),
plot.background = element_rect(fill = bk_clr))
bp6 <- ggplot(df[df$machine=="Machine4",], aes(x=clone, y=value)) +
geom_boxplot(coef=1, outlier.shape=NA, lwd=0.3) +
geom_point(size=1.8, alpha=0.9) +
ggtitle("Machine 4") +
expand_limits(y=c(0.001,10^5)) +
facet_wrap(~ donor, nrow=1, scales="free_x") + scale_y_log10(expand = c(0, 0)) +
theme(axis.text.x= element_text(size=rel(1), colour = ln_clr, angle=45, hjust=1),
panel.spacing = unit(0.25, "lines"), plot.title = element_text(hjust=0.5),
strip.text.x = element_text(size=rel(1), face="bold", colour = ln_clr),
strip.background = element_rect(colour = ln_clr, fill = bk_clr, size = 1),
axis.line.x= element_line(size = 1.25, colour = ln_clr),
axis.line.y= element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank(),
axis.title.y= element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(fill = bk_clr),
panel.border = element_blank(),
plot.background = element_rect(fill = bk_clr))
# Plot all 4 graphs and saves them as a output file
png(filename="graph3.png", width= 9, height= 7.5, units = "in", res=600)
multiplot(bp3, bp4, bp5, bp6, cols=2)
dev.off()
Alternatively, if I set the "strip.text.x = " and the "strip.background =" as element_blank(). I can generate the below:
Thanks for the suggested duplicate, this is however not only about the labels, but is also about adjusting the points themselves so they do not overlap.
have a quick look at the plot below...
I need the coloured points, and their corresponding labels, to never overlap. They should be clustered together and all visible, perhaps with some indication that they are spaced and not 100% accurate, perhaps some sort of call out? Open to suggestions on that.
I've tried adding position = 'jitter' to both geom_point and geom_text, but that doesn't seem to be working (assume it is only for small overlaps?)
Ideas?
# TEST DATA
srvc_data <- data.frame(
Key = 1:20,
X = sample(40:80, 20, replace = T),
Y = sample(30:65, 20, replace = T)
)
srvc_data$Z <- with(srvc_data,abs(X-Y))
t1<-theme(
plot.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
axis.line = element_line(size=.4)
)
main_plot <- ggplot(srvc_data, aes(x = X, y = Y),xlim=c(0,100), ylim=c(0,100)) +
t1 +
theme_bw() +
labs(x="X", y="Y") +
scale_x_continuous(limits = c(0, 100)) +
scale_y_continuous(limits = c(0, 100)) +
geom_abline(intercept = 0, slope = 1, colour="blue", size=34, alpha=.1)+
geom_abline(intercept = 0, slope = 1, colour="black", size=.2, alpha=.5,linetype="dashed")+
geom_point(size = 7, aes(color = Z), alpha=.7) +
scale_color_gradient("Gap %\n",low="green", high="red")+
coord_fixed()+
geom_text(aes(label=Key,size=6),show_guide = FALSE)
main_plot
Produces this plot (of course with your random data it will vary)
Thanks in advance.
Here's your plot with ggrepel geom_text_repel:
library(ggrepel)
# TEST DATA
set.seed(42)
srvc_data <- data.frame(
Key = 1:20,
X = sample(40:80, 20, replace = T),
Y = sample(30:65, 20, replace = T)
)
srvc_data$Z <- with(srvc_data,abs(X-Y))
t1<-theme(
plot.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
axis.line = element_line(size=.4)
)
ggplot(srvc_data, aes(x = X, y = Y),xlim=c(0,100), ylim=c(0,100)) +
t1 +
theme_bw() +
labs(x="X", y="Y") +
scale_x_continuous(limits = c(0, 100)) +
scale_y_continuous(limits = c(0, 100)) +
geom_abline(intercept = 0, slope = 1, colour="blue", size=34, alpha=.1)+
geom_abline(intercept = 0, slope = 1, colour="black", size=.2, alpha=.5,linetype="dashed")+
geom_point(size = 7, aes(color = Z), alpha=.7) +
scale_color_gradient("Gap %\n",low="green", high="red")+
coord_fixed()+
geom_text_repel(aes(label=Key,size=6),show_guide = FALSE)
Running in R this code:
# example data
x = runif(14, 0.0, 1.0)
norm = x/sum(x)
data = data.frame(replicate(17,sample(norm)))
require(ggplot2)
require(reshape2)
data$no <- seq_len(nrow(data))
data_molten <- melt(data, id.vars = "no")
data_molten[data_molten == 0] <- NA
View(data_molten)
# ggplot
ggplot(data_molten[!is.na(data_molten$value),], aes(x = variable, y = value, fill = factor(no))) +
geom_bar(stat = "identity") +
scale_fill_hue(l=40) + facet_grid(no~.) + theme_minimal() +
theme(legend.position="none",
axis.text.x = element_text(angle = 90, colour="black", vjust = 0.5, hjust=1, size=16),
axis.title.x = element_blank(), axis.title.y = element_blank(),
axis.line.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank(),
strip.text.y=element_text(size = 16, colour="black", family="", angle=00,hjust = 0),
panel.grid=element_blank(),
axis.line=element_line(size = 1, colour = "black", linetype = "solid"),
axis.ticks.x=element_line(size = 1, colour = "black", linetype = "solid"),
panel.background=element_blank())
produces this plot:
Anybody knows how can I add a vertical line between the right side of the plot and the layers' labels (the 1, 2, 3, ..., 14) which have a tick per layer's label, keeping enough space between the plot, the axis and the labels?
EDIT:
Running
num_var_x = 14
num_var_y = 17
x = runif(num_var_x, 0.0, 1.0)
norm = x/sum(x)
data = data.frame(replicate(num_var_y,sample(norm)))
## preparing dataset for ggplot
require(ggplot2)
require(reshape2)
data$no <- seq_len(nrow(data))
data_molten <- melt(data, id.vars = "no")
data_molten_sort = data_molten[with(data_molten,order(no)),]
## removing elements from variable 'no' whose max. value is e.g. < 0.025
sequence = seq(from=1, to=(num_var_y*num_var_x-num_var_x)+1, by=num_var_x)
for(i in 1:length(sequence))
{
if(isTRUE((max(data_molten_sort$value[(sequence[i]):((num_var_x+sequence[i])-(1))])) < 0.025))
{
data_molten_sort$value[(sequence[i]):((num_var_x+sequence[i])-(1))] = NA
}
}
View(data_molten)
## preparing posterior exporting
#install.packages("Cairo"); "cairo" type in png() has a better quality
library("Cairo")
#preparing exporting
png(file="ggplot.png",type="cairo", width = 4, height = 5, units = 'in',pointsize=8,res=600)
## plotting
ggplot(data_molten[!is.na(data_molten$value),], aes(x = variable, y = value, fill = factor(no))) +
geom_bar(stat = "identity") +
scale_fill_hue(l=40) + facet_grid(no~., as.table=FALSE, scale="free_y", space = "free_y") + theme_minimal() +
geom_vline(xintercept=max(as.numeric(data_molten$variable)) + 0.586, size=0.3) +
theme(legend.position="none",
axis.text.x = element_text(angle = 90, colour="black", vjust = 0.4, hjust=1, size=8),
axis.title.x = element_blank(), axis.title.y = element_blank(),
axis.line.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank(),
strip.text.y=element_text(size = 8, colour="black", family="", angle=00,hjust = 0.1),
panel.grid=element_blank(),
axis.line=element_line(size = 0.3, colour = "black", linetype = "solid"),
axis.ticks.x=element_line(size = 0.3, colour = "black", linetype = "solid"),
panel.background=element_blank(), panel.margin = unit(0, "lines"))
## exporting barplot "ggplot.png" to directory
dev.off()
now the y line is continuous, plus other additions such as an exporting command.
http://i.imgur.com/C6h5fPg.png?1
Assuming that your original plot is saved in an object p1, this could be a solution:
p1 + geom_vline(xintercept=max(as.numeric(data_molten$variable))+0.5, size=1) + #data-dependent
scale_x_discrete(expand=c(0,0))+ #create nicer corner
theme(
#move labels slightly to the right with hjust
strip.text.y=element_text(size = 16, colour="black", family="", angle=00,hjust = 0.5)
)