Legend in R markdown - r

I can´t figure it out how to fit a legend with a graph in Markdown R.
My result looks like this.
plot_druhych_davek = ockovani %>%
ggplot(aes(x=datum,y=druhych_davek, color = kraj_nazev))+ #+ scale_y_log10()
geom_line(alpha = 0.8)+
labs(title = str_wrap( sprintf("Průběh druhých dávek očkování od: %s DO: %s", OD, DO),40) ,
x = "Datum",
y = "Počet dávek",
color = "kraj_nazev")+
theme_fivethirtyeight()+
theme(axis.title = element_text()) +
theme(legend.title = element_blank())
plot(plot_druhych_davek)

Sadly I dont have enough Rep to put this as a comment but you might be interested in
ggplot(xyz) + scale_color_xxx(guide = guide_legend(keywidth = xxx, keyhight = xxx))
this line of code lets you customize your legend quite granularily, however for me always involves a lot of trial and error. There are much more arguments than the ones I used within guide_legend(). Good luck!

Related

How to create a legend title in a ggplot2 line graph

I am creating a line graph using the ggplot2 package in R.
I cannot upload the data as it is for a study I am conducting for my final year project. So, I can only share the code with you.
This is the code for the APA formatted graph.
ggplot(accuracy_data,
aes(x = eccentricity, y = accuracy, group= speech_task)) +
geom_line(aes(linetype=speech_task)) +
scale_linetype_manual(values=c("twodash", "dotted", "solid")) +
geom_point(aes(shape = speech_task)) +
facet_grid(. ~ duration, labeller=labeller(duration = labels)) +
labs(x='Eccentricity (degrees of visual angle)', y='Accuracy of responses') +
theme_apa() +
theme(text=element_text(family='Times')) +
scale_x_continuous(breaks =c(5, 10, 15)) +
geom_errorbar(aes(ymin = accuracy - acc_sum$se , ymax = accuracy + acc_sum$se ), width=.1)
This produces a graph with a legend without a title, hence I am asking for help in creating a title for the legend.
I have tried a lot of different options however none work. I don't even get an error message.
These are the codes I have tried so far:
legend_title <- "Speech Task"
scale_fill_manual(legend_title,values=c("Conversation", "N-Back", "Silence"))
guides(fill=guide_legend(title="Speech Task"))
scale_fill_discrete(name = "Speech Task",
labels = c("Conversation", "N-Back", "Silence"))
labs(fill="Speech Task")
The following and final code I tried was the only one to produce a change in the graph. However because I have manually changed the point shape as well as line type it caused two legends to be made and only titled the line type legend.
labs(linetype= "Speech Task")
Please can I have some help :)
Seeing no data or final results I'm going on a hunch here.
I suspect you need to name shape and fill legends the same. So something along the lines of
scale_linetype_manual(name = legend_title, values = c("twodash", "dotted", "solid")) +
scale_fill_manual(name = legend_title, values = c("Conversation", "N-Back", "Silence")) +

Failed to change the subplot background when generating a grouped correlation matrix heat map using ggplot2 facet

I am a newbie for stack Overflow and r language.
Here is my problem.
I now have a dataframe with one variable called Type and other 14 variables whose correlation matrix heatmap needed to be calculated.
origin dataset
I already have an overall format using ggplot2, and the theme is default theme_grey but fine for me to view. The code is :
m<- melt(get_lower_tri(round(cor(xrf[3:16], method = 'pearson', use = 'pairwise.complete.obs'), 2)),na.rm = TRUE)
ggplot(m, aes(Var1, Var2, fill = value)) +
geom_tile() +
scale_fill_gradient2(low = 'skyblue4',
high = 'coral2',
mid = 'white',
midpoint = 0,
limit = c(-1, 1),
space = "Lab",
name = 'Person\nCorrelation') +
theme_grey()+
coord_fixed() +
theme(axis.title = element_blank())
The result is fine and the background looks good to view.
But when I managed to generate a grouped correlation matrix heatmap, I found that no matter how hard I tried (using theme(panel.background = element_rect()) or theme(panel.background = element_blank())), the subplot backgrounds won’t change and remain this ugly grey which is even different from the overall one.
Here is my code:
Type = rep(c('(a)', '(b)', '(c)','(d)', '(e)', '(f)', '(g)', '(h)', '(i)', '(j)'), each = 14^2)
# Get lower triangle of the correlation matrix
get_lower_tri<-function(x){
x[upper.tri(x)] <- NA
return(x)
}
df2 <- do.call(rbind, lapply(split(xrf, xrf$Type),
function(x) melt(get_lower_tri(round(cor(x[3:16], method = 'pearson', use = 'pairwise.complete.obs'), 2)),na.rm = FALSE)))
my_cors <- cbind(Type,df2)
my_cors %>%
ggplot(aes(Var1, Var2, fill = value)) +
geom_tile() +
scale_fill_gradient2(low = 'skyblue4',
high = 'coral2',
mid = 'white',
midpoint = 0,
limit = c(-1, 1),
space = "Lab",
name = 'Person\nCorrelation') +
theme_grey()+
coord_fixed() +
theme(axis.title = element_blank(),
panel.background = element_rect(fill = 'grey90',colour = NA))+
facet_wrap("Type",ncol = 5, nrow = 2)
Isn’t the facet subplot backgrounds the same as the overall one if using the same theme? And how can I change it?
Update:sorry! It’s my first time to raise a question and it’s not a good one!
xrf is my original dataset...But now I have figured out why thanks to Tjebo and those who comment my faulty questions.It’s very instructive to me!!
scale_fill_gredient2(...,na.value = 'transparent') will solve it.The default value of this parameter is "grey50" which I took as the background color.
I am truly sorry for asking such a silly question, and I really really appreciate you guys’s nice comment for a rookie! Thank you guys!

ggplot2 data labels outside margins

I'm making many figures in ggplot2 using a for loop, but my data labels are extending beyond the plot margin. I've tried using expand, but it only works for some figures. When I try to use par(mar) I get this error message:
Error: Don't know how to add o to a plot.
I also tried just using ggsave to save as a really wide file, but 1) that looks odd and 2) that won't work for making so many different figures.
Does anyone know of any other workarounds? Ideally a way to have the inner plot margins automatically set per figure based on the length of the bars + data labels. Below is the code I'm using and an example figure (you can see the bar for 'x' is outside the margin). Thank you in advance!
for (i in each) {
temp_plot = ggplot(data= subset(Data, Each == i)) +
geom_bar(stat = "identity",
aes(x = reorder(Letter, +Number), y = Number, fill = factor(Category))) +
xlab("Letters") +
ggtitle(paste0("Title"), subtitle = "Subtitle") +
coord_flip() +
theme_classic() +
theme(plot.title = element_text(hjust = 0.5, size=16),
plot.subtitle = element_text(hjust = 0.5)) +
scale_fill_manual(values = c("#00358E", "#00AFD7"),
name= "Category",
labels=c("This","That")) +
geom_text(family="Verdana", size=3,
aes(label=Number2, x=reorder(Letter, +Number), y=Number),
position=position_dodge(width=0.8), hjust=-0.001) +
scale_y_continuous(labels = comma, expand = c(0.01,0)) +
scale_x_discrete(labels = letters)
ggsave(temp_plot, file=paste0("Example", i,".jpeg"))
}
I figured out a simple solution: + ylim(0, 130000)
scale_y_continuous(expand = expansion(mult = c(0, .1)) )

How to adjust the following ggplot2 graph?

I conduct a research about global education recently and the following graph is an important plot of my research.
ggplot(sam_data,aes(JOY,PV)) +
geom_line(aes(colour = Individualism))+
facet_grid(occupation~as.factor(Gender)) +
theme(legend.key.height = unit(2.0,"cm"),legend.text = element_text(size = 5,face = "plain")) +
scale_color_continuous("Individualism",labels=sam_data$country,breaks =sam_data$Individualism)+
geom_smooth()
And the problem is obvious :
1) The correlation line of different countries is all combined into one line, instead of different lines when segmented into gender and occupation.
2) The legend is a mess as I want to make it shown clear the countries corresponding to their individualism level. However, I tried to adjust many parameters of the legend and it did not work so much.
3) Also, I do not know how to delete the white gap produced by the breaks parameter. Any thoughts would be great!
I have solved the second problem by adjusting the aes parameter in ggplot function. The new code of mine is as follows
ggplot(sam_data,aes(JOYSCIE,PV1SCIE,group = CNTRYID)) +
geom_point(aes(color = Individualism.comp4))+
facet_grid(recode.OCOD3~as.factor(Gender0women1men)) +
theme(legend.key.height = unit(3.0,"cm"),legend.text = element_text(size = 5,face = "plain")) +
scale_color_gradientn("Individualism",labels=sam_data$CNTRYID,breaks =sam_data$Individualism.comp4,colors = rainbow(4))+
scale_x_continuous(limits = c(-2,2))

Automatically resizing legend for a plot made using ggplot2 such that the entire legend lies within the boundary of the layer

I have some data here
I read the data into a data frame and then plot this data with this following code,
# Reading data from a .csv file into a data frame
df <- read.table("newcsv_file.csv",header=T,sep="\t" )
# Now melting the data frame prior to plotting
df_mlt <- melt(df, id=names(df)[1], measure=names(df)[c(2, 6, 11,16,21,26,31,36,41,46,51,106,111,116,121,126,131,136,141,146,151)], variable = "cols")
# plotting the data
plt_fit <- ggplot(df_mlt, aes(x=x,y= value, color=cols)) +
geom_point(size=2) +
geom_smooth(method = "lm", se = FALSE) +
scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x), labels = trans_format("log10", math_format(10^.x))) +
annotation_logticks(sides = "rl") +
theme_bw() +
theme(legend.text=element_text(size=12), legend.title=element_text(size=12))+
theme(axis.text=element_text(size=14)) +
theme(axis.title=element_text(size=14,face="bold")) +
labs(x = "x", y = "y") +
scale_color_discrete(name = "values", labels = c("0","-0.1","-0.2","-0.3","-0.4","-0.5","-0.6","-0.7","-0.8","-0.9","-1","+0.1","+0.2","+0.3","+0.4","+0.5","+0.6","+0.7","+0.8","+0.9","+1")) +
guides(colour = guide_legend(override.aes = list(size=3),nrow=2,title.position = 'top',title.hjust=0.5,legend.direction = "horizontal")) +
theme(legend.position = 'bottom', legend.margin=unit(1,"cm"),legend.background = element_rect(fill ='gray94')) +
theme(plot.margin=unit(c(0,2,0,0),"mm"))
The resulting plot looks like this, the problem here is that the right most edge of the legend is cropped.
I use +theme(legend.margin=unit(1,"cm")) but this does not seem sufficient. Could someone please let me know what I can change to display the full legend properly in the plot.
Thanks.
The code is fine. The problem is the size of your plot window. Try making it wider and you'll see the whole legend.
Also,
ggsave("plot_fit.pdf",plot_fit)
will create a pdf where the full legend is displayed.
After changing the width and height of the plot using the following code,
ggsave(file="new_png_file.png",width=22,height=21,units=c("cm"), dpi=600)
Yields a plot such as this,

Resources