Wrapping legend in r - r

Is there a way to wrap the legend so that it goes to the new line or column in r? Even tried to reduce the size but din't work.
Image of my plot-notice legend in overflowing
p <- ggplot(cohort.chart.cl, aes(x=month, y=clients, group=cohort))
p + geom_area(aes(fill = cohort)) +
scale_fill_manual(values = reds(nrow(cohort.clients))) +
ggtitle('Customer Cohort') + theme(legend.position="bottom",panel.background=element_rect(fill = "light grey"),legend.text = element_text(size = 7),legend.key.size = unit(0.25, "cm"))

You can use guides() and pick the number of rows of your legend that looks most attractive:
p <- ggplot(cohort.chart.cl, aes(x=month, y=clients, group=cohort))
p + geom_area(aes(fill = cohort)) +
scale_fill_manual(values = reds(nrow(cohort.clients))) +
ggtitle('Customer Cohort') + theme(legend.position="bottom",panel.background=element_rect(fill = "light grey"),legend.text = element_text(size = 7),legend.key.size = unit(0.25, "cm")) +
guides(fill = guide_legend(nrow = 3)) # or experiment with other numbers of rows

Related

How to manually change the fill color of barplot when stat='count' in ggplot2

Here is my data:
mydata=data.frame(compliance=c("Yes","Yes","No","Yes","Yes","No"),
doctor=c("Sam","Sam","Sam","Bob","Fred","Bob"))
I tried to creat the barplot as below:
ggplot(data=mydata, aes(x=doctor,fill=compliance)) +
geom_bar(stat="count",width=0.4) +
geom_text(stat='count',aes(label=..count..), vjust=-0.3) +
expand_limits(y = c(0, 3)) +
labs(y = NULL, x= NULL) +
theme(legend.title = element_blank()) +
scale_fill_manual(values = c("#00BFC4","#F8766D")) +
scale_fill_discrete(limits = c("Not found","Compliance"))
However, the bar color is still in grey, I'd like to know how to fix this problem, thanks!
Don't use two scale_.*. You can add labels in scale_fill_manual itself.
library(ggplot2)
ggplot(data=mydata, aes(x=doctor,fill=compliance)) +
geom_bar(stat="count",width=0.4) +
geom_text(stat='count',aes(label=..count..), vjust=-0.3) +
expand_limits(y = c(0, 3)) +
labs(y = NULL, x= NULL) +
theme(legend.title = element_blank()) +
scale_fill_manual(values = c("#00BFC4","#F8766D"), labels = c("Not found","Compliance"))

Unable to display shape legend in ggplot

I have the following code :
cols <- c("Bonus"=maroon ,
"Limit"=grey)
a <- ggplot(periodtreatments, aes(x=names, width=.2)) +
geom_point(aes(y=bonus_coefs, colour="Bonus"), stat="identity", position = position_nudge(x = -.1), shape=16) +
geom_point(aes(y=limit_coefs, colour="Limit"), stat="identity", position = position_nudge(x = .1), shape=15)+
geom_errorbar(aes(ymin=bonus_upper, ymax=bonus_lower, width=0.09), size =0.8, stat="identity", colour=maroon, position = position_nudge(x = -.1)) +
geom_errorbar(aes(ymin=limit_lower, ymax=limit_upper, width=0.09), size =0.8, stat="identity", colour=grey, position=position_nudge(x = .1)) +
scale_y_continuous(name="Treatment effect (minutes/day)") +
theme_classic() +
#theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
labs(x = "") +
theme(legend.text.align = 0,
legend.key.height = unit(1, "cm"),
legend.position="bottom") +
theme(legend.margin=margin(0,0,0,0),
legend.box.margin=margin(-10,-10,-10,-10)) +
theme(axis.text.x = element_text(colour="black")) +
coord_cartesian(ylim = c(-70, 5)) +
theme(legend.text=element_text(size=11)) +
theme( # remove the vertical grid lines
panel.grid.major.x = element_blank() ,
# explicitly set the horizontal lines (or they will disappear too)
panel.grid.major.y = element_line( size=.05, color="grey" )
)+
scale_colour_manual(name = "", values=cols,
labels = c("Bonus", "Limit"))+
scale_shape_manual(name = "",
labels = c("Bonus", "Limit"),
values = c(16, 15))
But the "scale_shape_manual" legend does not work.
In fact here is what my plot look like
Why does the Bonus show as a sqaure whereas its shape is 16 = point ???
Please help me i am so helpless

Change the font size of variable names in ggplot

I am not able to increase the font size of the names of the variables in a graphic realized with ggplot.
I tried to include these codes inside ggplot code, but unsuccessfully :
theme(text = element_text(size=20))
theme(axis.text=element_text(size=20))
theme(axis.title=element_text(size=14))
theme_grey(base_size = 20)
geom_text(size=20)
My code is :
library(ggplot2)
library(reshape2)
dataplot <- read.csv("/Documents/R.csv",header=T,sep=";")
dataPlotMelt <- melt(data = dataplot, id.vars = c("variable"),variable.name = "Method",value.name = "SMD")
varNames <- as.character(dataplot$variable)
dataPlotMelt$variable <- factor(dataPlotMelt$variable,levels = varNames)
ggplot(data=dataPlotMelt,mapping=aes(x=variable,y=SMD,group=Method, color=Method))+
ylab("Standardizedmeandifference(%)")+
xlab("") +
geom_point(aes(shape=Method),size=2) +
geom_hline(yintercept=15,color="black",size=0.1,linetype="dashed") +
geom_hline(yintercept=-15,color="black",size=0.1,linetype="dashed") +
coord_flip() +
theme(axis.text.x=element_blank()) +
scale_y_continuous(breaks=c(-65,-15,15,105)) +
theme_bw() +
theme(legend.text=element_text(size=12)) +
theme(legend.title=element_blank(),legend.key=element_blank()) +
scale_colour_manual(values=c("grey","black"))
I'd like to increase the font size of the names of the variables in the graphic and, besides, increase the text "Standardized mean difference (%)" and remove the vertical line between the yintercept and ybreak on both sides
new graphic
Thank you Richard for giving me the solution.
As you suggested I used theme after theme_bw
I managed to suppress the useless vertical lines as well with the command theme(panel.grid.minor = element_blank())
Here is the new code for ggplot :
ggplot(data = dataPlotMelt, mapping = aes(x = variable, y = SMD,group = Method,
color = Method)) +
ylab("Standardized mean difference (%)") + xlab("") +
geom_point(aes(shape = Method),size=2) +
geom_hline(yintercept = 15, color = "black", size = 0.1, linetype = "dashed") +
geom_hline(yintercept = -15, color = "black", size = 0.1, linetype = "dashed") +
coord_flip() +
theme(axis.text.x = element_blank()) +
scale_y_continuous(breaks=c(-65,-15,0,15,105)) +
theme_bw() + theme(legend.text = element_text(size=13)) +
scale_colour_manual(values= c("grey","black")) +
theme(axis.text.y = element_text(size=12)) +
theme(axis.title.x = element_text(size=13)) +
theme(panel.grid.minor = element_blank()) +
theme(legend.title = element_blank(), legend.key=element_blank())

R ggplot2: remove panel spacing from strip text

I am trying to create a barplot with two x-axis (grouped x-axis):
# read data
tmp <- read.table(text = "label CNV_x CNV_Type
17p -1 Loss
9p -1 Loss
16q 1 Gain
10p 1 Gain
8q 1 Gain
13q 1 Gain", header = T)
tmp$CNV_Type <- relevel(tmp$CNV_Type, ref = 'Loss')
# plot
ggplot(tmp, aes(x = label, y = CNV_x)) +
geom_bar(stat = 'identity') +
theme_bw() +
geom_hline(yintercept = 0) +
coord_flip() +
facet_wrap(~CNV_Type, strip.position = "bottom", scales = "free_x") +
theme(panel.spacing = unit(0, "lines"),
strip.background = element_blank(),
strip.placement = "outside",
panel.border = element_rect(colour = NA))
This creates a plot like this:
This plot shows 0.00 twice on x-axis and I can't figure out a way to remove the spacing between the two vertical lines separating the strips (one is Gain and other is Loss).
Any help would be much appreciated. Thanks!
UPDATE: I added scale_y_continuous(expand = c(0, 0)) as suggested below:
ggplot(tmp, aes(x = label, y = CNV_x)) +
geom_bar(stat = 'identity') +
theme_bw() +
geom_hline(yintercept = 0) +
scale_y_continuous(expand = c(0, 0)) +
coord_flip() +
facet_wrap(~CNV_Type, strip.position = "bottom", scales = "free_x") +
theme(panel.spacing = unit(0, "lines"),
strip.background = element_blank(),
strip.placement = "outside",
panel.border = element_rect(colour = NA))
This creates a plot like this:
The only issue now is there is no spacing between the bars and the left and right margins of the plot - not sure why that happened.
I would not use facets here. A couple of options. You could indicate the type by colour:
tmp %>%
ggplot(aes(label, CNV_x)) +
geom_col(aes(fill = CNV_Type)) +
geom_hline(yintercept = 0) +
coord_flip() +
scale_fill_manual(values = c("darkorange", "skyblue3"))
And/or add the labels for type to the plot using annotate. That requires some manual fiddling with x, y and expand to get it right:
tmp %>%
ggplot(aes(label, CNV_x)) +
geom_col() +
geom_hline(yintercept = 0) +
coord_flip() +
annotate("text",
label = c("Loss", "Gain"),
x = c(7, 7),
y = c(-0.5, 0.5)) +
scale_x_discrete(expand = c(0.1, 0.1))

putting two different legends in two columns in ggplot2

I have the following reproducible code which gets me the plot listed below:
require(ggplot2)
set.seed(123)
ChickWt <- data.frame(ChickWeight, AR = sample(c("p=0", "p=1", "hat(p)"), size = 578, replace = T))
exprvec <- expression( p==hat(p), p==0, p==1)
p1 <- ggplot(ChickWt, aes(x=Time, y=weight, colour=Diet, Group = Chick, linetype = AR)) + geom_line()
p1 <- p1 + scale_linetype_manual(values=c(2,4,1), labels = exprvec,name="AR order") + theme_bw() + theme(legend.justification=c(1,-0.2), legend.position=c(0.3,0.2), legend.text=element_text(size=10), legend.title=element_text(size=10), axis.title.x=element_text(size=10), axis.title.y=element_text(size = 10), legend.key = element_blank(), legend.background = element_rect(color="black",size = 0.1)) + ylim(c(0,400)) + guides(fill=guide_legend(ncol=2))
but I would like the legend on Diet and AR order in two separate columns. How do I get this to work? Clearly, the guides(fill=guide_legend(ncol=2)) has no effect, perhaps because these are two separate legends.
Thanks for suggestions!
The reason that guides(fill=guide_legend(ncol=2)) does not work is because it only refers to the fill-legend and not to the linetype-legend. You can position the legends next to each other by using legend.box = "horizontal":
ggplot(ChickWt, aes(x=Time, y=weight, colour=Diet, Group = Chick, linetype = AR)) +
geom_line() +
scale_linetype_manual(values=c(2,4,1), labels = exprvec,name="AR order") +
theme_bw() +
theme(legend.justification=c(1,-0.2),
legend.position=c(0.3,0.2),
legend.text=element_text(size=10),
legend.title=element_text(size=10),
axis.title.x=element_text(size=10),
axis.title.y=element_text(size = 10),
legend.key = element_blank(),
legend.background = element_rect(color="black",size = 0.1),
legend.box = "horizontal") +
ylim(c(0,400))
which gives:

Resources