ggplot legend at top but below title? - r

Is there a way to make ggplot place the legend on top but below the title?
As an example...
..produced with the following code:
carrots<-list(Yield=c(345,226,74,559,288,194),
Field=c("A","B","C","D","E","F"),
Breed=rep(c("Long","Short"),each=3))
carrots<-data.frame(carrots)
ggplot(carrots,aes(y=Yield,x=Field,fill=Breed)) +
geom_bar() +
opts(title="Title",
legend.direction = "horizontal",
legend.position = "top") +
labs(fill="")
Any suggestions would be greatly appreciated?

Edit Ignore this. The issue is not longer a problem.
But the code has been updated so that it no longer throws an error.
While waiting for the next version, you can fine tune within ggplot2. For instance:
ggplot(carrots, aes(y = Yield, x = Field, fill = Breed)) +
geom_bar(stat = "identity") +
theme(
plot.margin = unit(c(2, 1, 1, 1), "cm"),
plot.title = element_text(size = 30, face = "bold", colour = "blue", vjust = 7),
legend.direction = "horizontal",
legend.position = c(0.1, 1.05)) +
ggtitle("Title") +
labs(fill = "")

Related

Placing a Legend Title Above a Horizontal Legend Already Positioned at the Top of a Barplot ggplot

Issue:
I have done a lot of research and tried many different solutions and I could not find an answer to my problem, at least not one that worked for me. I am attempting to place the legend title 'Species' above the horizontally placed legend positioned at the top of a barplot (see below) and for it to be centred.
For instance:
Solution 1
Solution 2
Solution 3
In general, I believe and I am using the correct ggplot() commands and I have tried following the examples from other StackOverflow questions. Whatever code I use, nothing happens and the title continues to remain at the lefthand side of the horizontal legend.
Would anyone be able to lend a hand?
Many thanks in advance.
R-Code
#Open Graphics Window
dev.new()
#Barplot
Whistle_Plot<-ggplot(Whistle_Subtype, aes(x = Whistle_Type_Sub, y = N, fill = Species)) +
geom_bar(stat="identity", position=position_dodge(), width = 0.6) +
scale_fill_grey(start = 0.25, end = 0.75) +
theme(axis.text.x = element_text(angle = 75, hjust = 1), text = element_text(size=9)) +
theme(panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank()) +
theme(axis.line.x = element_line(color="black", size = 0.8),
axis.line.y = element_line(color="black", size = 0.8)) +
labs(size = 0.8, x = "Whistle Subtypes", y = "Counts of Whistle Subtypes") +
theme(legend.position = 'top',
legend.direction = "horizontal") +
guides(color = guide_legend(title.position = "top",
# hjust = 0.5 centres the title horizontally
title.hjust = 0.5,
label.position = "bottom"))
#Set the limits of the y-axis scale
Whistle_Plot + scale_y_continuous(breaks=seq(0, 80, by=10))
Barplot
If you switch to guides(fill = ...) you should be able do it.
Try:
guides(fill = guide_legend(title.position = "top", title.hjust=0.5)
(thanks to #teunbrand, for minor correction)

Draw a vertical line from x axis straight up ggplot

I am trying to plot my ggplot with a vertical line that goes from 0 on the x-axis and straight up. I have tried to use geom_line, but I don't seem to get it to work. I would like something similar to the figure. This is my code so far.
ggplot(dat_plot, aes(x = values, y = ind, fill = "lightgrey", width = 0.5)) +
stat_summary(fun.data = quantiles_95, geom = "boxplot") +
ggtitle("Wild boar") +
ylab("") +
xlab("Effect") +
scale_y_discrete(labels = faktorer_vs) +
theme_classic() +
theme(legend.position = "none", axis.text = element_text(size = 10),
axis.title = element_text(size = 13), axis.line = element_line(colour = "black"),
plot.title = element_text(size = 18))

How to draw an empty ggplot with just the legend?

My question is very similar to this question, but it's not the same.
I am looking for a way to create an empty ggplot with just the legend. However, in contrast to the autohor of the question I linked at the top, I actually need to create just the legend with no plot area included in the image.
I tried the following code:
ggplot(NULL, aes(color = ""))+
geom_blank()+
scale_color_manual(values = "black", labels = "Something")+
guides(color = guide_legend())+
theme(legend.box.background = element_rect(color = "black"))
But I'm getting the opposite of what I want - I am getting an empty plot area with no legend, like this:
And I would like my end result to look like this (I drew this in Paint):
Any help would be appreciated!
You can make a normal plot, then play with theme to achieve the desired result.
library(ggplot2)
ggplot(data.frame(x = 1, y = 1, colour = 'Something'), aes(x, y, fill = colour))+
geom_point(alpha=0, shape = 0)+ # completely transparent rectangular point
scale_fill_manual(values='black', drop=FALSE) +
guides(fill = guide_legend(override.aes = list(alpha=1, size = 40)))+ # showing the point in the legend
theme(axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
legend.position = c(0.5, 0.5), # move the legend to the center
legend.title = element_blank(),
legend.text = element_text(size = 40),
legend.key = element_rect(fill='NA'),
panel.grid = element_blank(),
panel.border = element_rect(colour = "black", fill='white', size=1)
)
Get the legend how you want it to look, then extract it with cowplot::get_legend:
library(grid)
library(cowplot)
library(ggplot2)
grid.newpage()
grid.draw(get_legend(
ggplot(data.frame(x = 1, y = 1), aes(x, y, fill = "Something")) +
geom_col(size = 20)+
scale_fill_manual(values = "white", labels = "Something", name = "") +
theme_bw() +
theme(legend.box.background = element_rect(color = "black"),
legend.title = element_text(size = 30),
legend.key.size = unit(60, "points"),
legend.text = element_text(size = 24),
legend.key = element_rect(colour = "black"),
legend.box.margin = margin(20, 20, 20, 20))))

Plot legend to move left ggplot

I like to move the legend a bit further on the left But I am not getting how to do it.
Secondly, I also want to reduce the space between axis label and legend too
Can you please suggest something
the code is given below that I am using
The image of the graph is in the link below
"tooltip"
ggplot(Q6_m, aes( choice,temp,fill=Answer ))+
geom_bar(position = position_stack(reverse = TRUE), stat="identity") +
coord_flip() +
xlab("") +
ylab("Number of responses") +
scale_fill_brewer(type = "div") +
theme(axis.text=element_text(size=8),
axis.title=element_text(size=8,face="bold"), legend.title = element_blank(),
legend.text=element_text(size=7)) +
ggtitle("Q6:Rate your ability to perform the following procedures WITHOUT attending assistance?")+
theme(plot.title = element_text(color = "black", size = 7.5, face = "bold", hjust = 1))+
facet_wrap(~gender,scales = "free_x")+
theme(legend.position="bottom", legend.direction = "horizontal",legend.key.size = unit(0.5,"line")
)
You should use legend.justification to get the legend on the left side of the plot and legend.margin to reduce the space between axis labels and the legend:
ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species))+
geom_boxplot()+
theme(legend.position = "bottom",
legend.justification = c(0,1),
legend.margin = margin(t = -15, r = 0, b = 0, l = 0, unit = "pt"))
Does it answer your question ?

Unable to customize strip in facet_grid

I am trying to customize the strip in facet_grid function.
My graph currently looks like:
I successfully changed the background of strip to purple, however, I could not change the border color to black, even though I set the color to 'black' in the function.
Also, I want the space between text and the rectangle to be larger so that it will looks nicer. How should I achieve this?
My codes looks like:
plot.density <- ggplot(df_densityWindow, aes(x = idx, y = density, color = factor(location))) +
geom_bar(stat = 'identity', fill = 'white') +
facet_grid(marker ~ case, scales = 'free') +
theme(strip.background = element_rect(colour="red", fill="#CCCCFF")) +
scale_color_manual(name = 'Regions',values = c("#F26969", "#02f527",'#F2F2C6')) +
background_grid(major = 'y', minor = "none") + # add thin horizontal lines
xlab('Index') +
ylab(expression(paste('Density/', mm^2, ))) +
theme(axis.title = element_text(size = 28)) +
theme(axis.text = element_text(size = 26)) +
theme(legend.text = element_text(size = 16)) +
theme(legend.title = element_text(size = 18)) +
panel_border() # and a border around each panel
plot(plot.density)
If necessary, the data could be downloaded here:
data
Thank you!
Your colour specification for strips works without error for me. The spacing between the strip text and box can be increased by setting the margin argument at the strip.text theme:
ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
geom_point() +
facet_grid(Species ~ rev(Species)) +
theme(strip.background = element_rect(colour="red", fill="#CCCCFF"),
strip.text = element_text(margin = margin(10, 10, 10, 10)))
Possible debug strategy:
Reproduce code above
1A. If that doesn't work, check if your ggplot versions is ~3.2-ish
1B. If that does work, proceed to 2.
Try to remove and place back lines of plotting to see where the error occurs
I'm particularly unfamiliar with panel_border() and background_grid(), so you could try those first.
EDIT: Plot based on data and code provided
ggplot(data, aes(x = idx, y = density, colour = factor(location))) +
geom_col(fill = "white") +
scale_color_manual(name = 'Regions',values = c("#F26969", "#02f527",'#F2F2C6')) +
facet_grid(marker ~ case, scales = "free") +
xlab('Index') +
ylab(expression(paste('Density/', mm^2, ))) +
theme(strip.background = element_rect(colour = "red", fill = "#CCCCFF"),
strip.text = element_text(margin = margin(10, 10, 10, 10)),
axis.title = element_text(size = 28),
axis.text = element_text(size = 26),
legend.text = element_text(size = 16),
legend.title = element_text(size = 18),
# Improvised based on missing functions
panel.grid.major.x = element_blank(),
panel.grid.major.y = element_line(colour = "grey90"),
panel.background = element_rect(fill = "white", colour = NA),
panel.border = element_rect(colour = "grey90", fill = NA))

Resources