Plot legend to move left ggplot - r

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 ?

Related

Fixing margins in ggplot2

I have a plot whose margins are slightly askew and need to be removed. So there should be no empty grey along the bottom or at the left and right of the plot. The dots should go right against the axis's. I think part of the problems may be my last two annotation lines. I tried adding + theme(plot.margins = unit(c(0.1,0.1,0.1,0.1), "cm")) in the last line that defines my plot but this just returns an error:
Error: Theme element `plot.margins` is not defined in the element hierarchy.
`
pvalplot<-function(var, maintitle) {
pvalall<-as.data.frame(c(t(var)))
pvalall$Sample_Size<-c((1:(5*162)),(1:(11*162)),(1:(3*162)),(1:(5*162)),(1:(13*162)),(1:(3*162)),(1:(5*162)))
pvalall$Domain<-c(rep("Physical",5*162),rep("Perinatal",11*162),rep("Developmental",3*162),
rep("Lifestyle-Life Events",5*162),rep("Parental-Family",13*162),rep("School",3*162),
rep("Neighborhood",5*162))
pvalall$Domain <- factor(pvalall$Domain,
levels = c("Physical", "Perinatal", "Developmental",
"Lifestyle-Life Events", "Parental-Family",
"School","Neighborhood"))
pvalall[,1]<-ifelse(pvalall[,1]<1e-20,1e-20,pvalall[,1])
names(pvalall)[1]<-"P-Values"
pvalexp.labels= rep("",45*162)
for (i in c(1:45)){
j=i*162-81
pvalexp.labels[j]=rownames(var)[i]
} #makes list of empyt labels that w
p<-ggplot(pvalall,aes(x = 1:nrow(pvalall), y = -log10(pvalall[,1])))+
geom_point(aes(color = Domain,size=5),
alpha = 0.7, size=1)
p+ylab(expression(atop(" -log10(P-Values)")))+
ylim(0,20)+
xlab(element_blank())+
theme(legend.title=element_blank())+
scale_x_continuous( breaks=c(1:45)*162-81, labels = rownames(var))+
theme_classic()+
theme(axis.title.x = element_blank())+
theme(axis.ticks.x = element_blank())+
theme(axis.title.y = element_text(size = 25))+
theme(text = element_text(size=25))+
theme(legend.title=element_blank())+
theme(legend.position=c(0.8,0.7))+
geom_abline(slope=0,intercept=-log10(c(var)[astsa::FDR(c(var))]),linetype = "dashed")+
geom_abline(slope=0,intercept=5.2,linetype = "dashed")+
ggtitle(maintitle)+
theme(plot.title = element_text(hjust = 0.5))+
theme(
legend.box.background = element_rect(),
legend.box.margin = margin(6, 6, 6, 6))+
theme_update(axis.text.x = element_text(angle = 35, size = 6.5, vjust = 1, hjust=1, color = "black")) +
annotate("text", label = expression(paste("FDR P-value","=0.05")),size=5, x=1000,y=-log10(c(var)[astsa::FDR(c(var))])-0.5, color="black",parse=TRUE)+
annotate("text", label = expression(paste("Bonferroni P-value","=0.05")),size=5, x=1200,y=5.7, color="black",parse=TRUE)
}#end of plotting
You can insert a line
scale_y_continuous(expand = c(0, 0)) +
in your plot command chain.

Increase Vertical Spacing between Legend Key in ggplot2

How can I increase vertical spacing between legend keys:
p1 <- ggplot(data = HSS, mapping = aes(x = EVENT, y = HSS, fill = TIME)) +
geom_bar(stat = "identity",width=0.7, colour = "black", position = position_dodge(0.7)) +
scale_fill_manual("HSS", values = c("deepskyblue3", "indianred2"),
labels = c("1200 UTC (0.049)", "0000 UTC (0.031)")) + theme_bw()
p1 <- p1 + scale_y_continuous(expand = expansion(mult = c(0.0085, -0.085)),
limits = c(-0.03,0.5), breaks = c(-0.03,-0.01, 0.01, 0.03, 0.05, 0.07,0.09,0.11,0.13,0.15,0.17,
0.19, 0.21,0.23,0.25,0.27,0.29,0.31,0.33,0.45),
labels = c("-0.03","-0.01","0.01","0.03","0.05","0.07","0.09","0.11","0.13","0.15","0.17",
"0.19","0.21","0.23","0.25","0.27","0.29","0.31","0.33","0.45")) +
theme(axis.text.x=element_text(color = "black", size=12, face = "bold", angle=90, vjust=.5,
hjust=0.8)) +
theme(axis.text.y = element_text(color = "black", size=12, face = "bold"))
p1 <- p1 + theme( axis.line = element_line(colour = "black", size = 0.5, linetype = "solid")) +
labs( y = "HSS")
p1 <- p1 + theme(axis.title=element_text(colour = "blue2" ,size=14,face="bold", vjust = 0.1))
p1 <- p1 + theme(legend.position=c(0.98,0.98)) + theme(legend.title=element_blank(),
legend.text = element_text(face = "bold", size = "12"),
legend.box.background = element_rect(size=0.7, linetype="solid"),
legend.justification = c("right", "top"),
legend.box.margin = margin(1, 1, 1, 1)
)
p1
I tried using legend.key.height legend.spacing.y guide but it only stretched legend keys without adding space between them. Also how can I remove alternate lables (encircled) of Y-axis keeping tickmark with plot.
After browsing ggplot2's source code for a bit, I come to the conclusion that the legend.spacing.y is only applied when the byrow = TRUE as argument to the legend.
Simplied example below.
library(ggplot2)
ggplot(iris, aes(Sepal.Width)) +
geom_density(aes(fill = Species)) +
guides(fill = guide_legend(byrow = TRUE)) +
theme(legend.spacing.y = unit(1, "cm"))
With regards to the labels, just remove the values from the breaks argument in scale_y_continuous() that you don't want to show, you're already specifying them manually.

Change the vertical spacing of one legend in ggplot?

I'm plotting two sets of data in ggplot2 with code like the following, which leads to me having two legends (ignore the ugly plot, this is just an example)
x <- ggplot(mtcars)+
theme_bw() +
theme(legend.position=c(0.8, 0.8), legend.direction="horizontal",
legend.key.size=unit(0.008, "cm"), legend.title=element_blank(),
legend.margin=margin(), legend.spacing = unit(0.04, "cm")) +
guides(colour = guide_legend(override.aes = list(size=6)), shape= guide_legend(override.aes = list(size=5))) +
geom_point(aes(x=mpg, y=cyl, colour=cyl))+
geom_point(aes(x=mpg, y = hp, shape=as.factor(carb)))
print(x)
The issue is that for me, the black shapes in the bottom are vertically too close together, I would like the two rows of black shapes to have more vertical space between them. I tried to use legend.spacing.y but it did not help at all, it only changed the space between the two individual legends (for cyl and carb). I would like to know if there's some theme command that would let me do something like legend.spacing(legend=carb, unit(0.1, "cm")) so it specifically acts on the carb legend.
Thanks!
You can use the keyheight argument in guide_legend
ggplot(mtcars) +
theme_bw() +
theme(
legend.position = c(0.8, 0.8),
legend.direction = "horizontal",
legend.key.size = unit(0.008, "cm"),
legend.title = element_blank(),
legend.margin = margin(),
legend.spacing = unit(0.04, "cm")
) +
guides(colour = guide_legend(override.aes = list(size = 6)),
shape = guide_legend(override.aes = list(size = 5), keyheight = 2)) +
geom_point(aes(x = mpg, y = cyl, colour = cyl)) +
geom_point(aes(x = mpg, y = hp, shape = as.factor(carb)))

Can this type of plot be done with ggplot2?

I am using R and ggplot2 to do some plots for publishing purposes. I have come across this plot and I would like to replicate it using ggplot2. However, I have never seen a plot like this made using ggplot2.
Can it be done with ggplot2? What about the text below the bars? I guess these will have to be hard coded in the ggplot2 codes. And how do you align those text?
This gets fairly close:
# Generate sample data (I'm too lazy to type out the full labels)
df <- data.frame(
perc = c(60, 36, 44, 41, 42, 57, 34, 52),
type = rep(c("blue", "green"), 4),
label = rep(c(
"Individual reports created as needed",
"Regular reports on single topics",
"Analytics using data integrated from multiple systems",
"Business unit-specific dashboards and visuals"), each = 2))
library(ggplot2)
ggplot(df, aes(1, perc, fill = type)) +
geom_col(position = "dodge2") +
scale_fill_manual(values = c("turquoise4", "forestgreen"), guide = FALSE) +
facet_wrap(~ label, ncol = 1, strip.position = "bottom") +
geom_text(
aes(y = 1, label = sprintf("%i%%", perc)),
colour = "white",
position = position_dodge(width = .9),
hjust = 0,
fontface = "bold") +
coord_flip(expand = F) +
theme_minimal() +
theme(
axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
strip.text = element_text(angle = 0, hjust = 0, face = "bold"))
A few explanations:
We use dodged bars and matching dodged labels with position = "dodge2" (note that this requires ggplot_ggplot2_3.0.0, otherwise use position = position_dodge(width = 1.0)) and position = position_dodge(width = 0.9), respectively.
We use facet_wrap and force a one-column layout; strip labels are moved to the bottom.
We rotate the entire plot with coord_flip(expand = F), where expand = F ensures that left aligned (hjust = 0) facet strip texts align with 0.
Finally we tweak the theme to increase the overall aesthetic similarity.
You can try using the data from the other answer. Differences are: we use scales::percent to draw percents. We use ggpubr::theme_transparent() theme to tweak as less as possible.
df$perc <- c(.60, .36, .44, .41, .42, .57, .34, .52)
ggplot(df, aes(label, perc, label=scales::percent(round(perc,2)),fill= factor(type))) +
geom_col(position = position_dodge(0.9), show.legend = F) +
geom_text(aes(y=0), position = position_dodge(0.9), size=5, hjust=-0.1, color="white", fontface="bold") +
scale_y_continuous("",labels = scales::percent) +
coord_flip(expand = F) +
facet_wrap(~label,scales = "free", strip.position = "bottom", ncol = 1) +
ggpubr::theme_transparent() +
xlab("") +
theme(strip.background = element_blank(),
strip.text = element_text(size = 12, face = "bold",hjust=0))
Maybe using facet wrap and adjusting the style?
dat <- data.frame(perc = c(60, 20, 90, 30), col = rep(c("gr1", "gr2"), 2),
text = c(rep("text1", 2), rep("text2", 2)))
ggplot(dat, aes(y = perc, x = col, fill = col)) +
geom_bar(stat = "identity", position = "dodge") +
coord_flip() +
facet_wrap(~text, strip.position = "bottom", ncol = 1)

ggplot legend at top but below title?

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 = "")

Resources