Change title in ggplot legend and update marker notation - r

I'm having trouble changing the title and the look of my legend in ggplot, right now it looks like this:
But I want the title to be "Whatever I please" and the colors representing the different data to be larger.(e.g. taking up the whole square instead of being a tiny circle)
For the title I tried changing:
theme(legend.position="top", legend.title='Whatever I please')
But ggplot doesn't accept this. How can I make this adjustments?

ggplot(...) + geom_point(...) +
labs(color = "Your title here") +
guides(color = guide_legend(override.aes = list(size = 5)))
You may need to change the size in the guide to get the look you want.

You could also use the name and guide arguments of the scale_colour_discrete function to do that:
library(ggplot2)
ggplot(mtcars, aes(x = hp, y = qsec, col = as.factor(cyl)))+
geom_point() +
scale_colour_discrete(name = "Whatever I please",
guide = guide_legend(override.aes = list(size = 10)))
The legend.title argument of the theme function only accepts element_text values (so your 'Whatever I please' there won't work), and is used mostly to change font related aspects of the legend title, not the text itself.

Related

ggplot only change the font of certain parts in the legend

Is it possible to put the scientific names of the fish in italics on the x-axis and in the legend and to use normal font for the rest?
In my case I would like that for example Barbatula barbatula (Bachschmerle) only Barbatula barbatula is in italics and (Bachscmerle) in the normal font
This is the bar chart right now
And this is a part of the data im using
My code is:
ggplot(R_Sandbach, aes(x = fct_infreq (Species), fill=Species ))+
geom_bar()+
theme_minimal()+
geom_text(aes(label=..count..), stat = "count", vjust = -.1, colour= "black")+
theme(axis.text.x = element_text(angle = 90, size = 5))+
xlab("Fischarten")+
ylab("Individuenanzahl")
ggtext is definitely a good option, although you can just manipulate aspects of your plot directly using theme as you've done in your question.
See an example below:
library(tidyverse)
ggplot() +
geom_blank() +
labs(x = "Fischarten", y = "Individuenanzahl", title = "My Super Awesome Title") +
theme(axis.title.x = element_text(face = "italic"),
plot.title = element_text(face = "italic"))
This produces a blank plot with the plot title and x axis both in italics. You can add as many changes into your theme() function as you like.
EDIT:
In the case of which you need specific words of your titles in italics, etc. you can manually incorporate html into your text and then format your plot to read this html.
In my personal experience this has sometimes caused issues with the general themes of ggplot.
Using this package library(mdthemes) solves the issues of html not being read as it should.
For example:
ggplot() +
geom_blank() +
labs(x = paste("<i>Fischarten</i>", "Other Title Stuff"), y = "Individuenanzahl", title = paste("My Super", "<i>Awesome Title</i>")) +
mdthemes::md_theme_classic()

Discrete value needed for graph, then I cannot delete as.factor from legend [duplicate]

I have the following plot like below. It was created with this command:
library(ggplot2)
df <- data.frame(cond = factor(rep(c("A", "B"), each = 200)),
rating = c(rnorm(200), rnorm(200, mean=.8)))
ggplot(df, aes(x=rating, fill=cond)) +
geom_density(alpha = .3) +
xlab("NEW RATING TITLE") +
ylab("NEW DENSITY TITLE")
Now, I want to modify the legend title from cond into NEW LEGEND TITLE.
So, I just added the following line add the end of the above code:
+labs(colour="NEW LEGEND TITLE")
But it doesn't work. What's the right way to do it?
This should work:
p <- ggplot(df, aes(x=rating, fill=cond)) +
geom_density(alpha=.3) +
xlab("NEW RATING TITLE") +
ylab("NEW DENSITY TITLE")
p <- p + guides(fill=guide_legend(title="New Legend Title"))
(or alternatively)
p + scale_fill_discrete(name = "New Legend Title")
I didn't dig in much into this but because you used fill=cond in ggplot(),
+ labs(color='NEW LEGEND TITLE')
might not have worked. However it you replace color by fill, it works!
+ labs(fill='NEW LEGEND TITLE')
This worked for me in ggplot2_2.1.0
Since you have two densitys I imagine you may be wanting to set your own colours with scale_fill_manual.
If so you can do:
df <- data.frame(x=1:10,group=c(rep("a",5),rep("b",5)))
legend_title <- "OMG My Title"
ggplot(df, aes(x=x, fill=group)) + geom_density(alpha=.3) +
scale_fill_manual(legend_title,values=c("orange","red"))
None of the above code worked for me.
Here's what I found and it worked.
labs(color = "sale year")
You can also give a space between the title and the display by adding \n at the end.
labs(color = 'sale year\n")
Since in your code you used ggplot(data, fill= cond) to create the histogram you need to add the legend title by also using "fill" in the label section i.e. +labs(fill="Title name"). If you were using a different type of plot where the code was ggplot(data, colour= cond), then you could use +labs(colour= "Title Name"). In summary, the lab argument has to match the aes argument.
I have used + guides(fill=guide_legend("my awesome title")) to change the legend title on geom_bar plots but it did not seem to work for geom_point.
There's another very simple answer which can work for some simple graphs.
Just add a call to guide_legend() into your graph.
ggplot(...) + ... + guide_legend(title="my awesome title")
As shown in the very nice ggplot docs.
If that doesn't work, you can more precisely set your guide parameters with a call to guides:
ggplot(...) + ... + guides(fill=guide_legend("my awesome title"))
You can also vary the shape/color/size by specifying these parameters for your call to guides as well.
I am using a facet_wrap in my ggplot and none of the suggested solutions worked for me except ArnaudA's solution:
qplot(…) + guides(color=guide_legend(title="sale year"))
Just to add to the list (the other options here didn't work for me), you can also use the function update_labels for ggplot:
p <- ggplot(df, aes(x=rating, fill=cond)) +
geom_density(alpha=.3) +
xlab("NEW RATING TITLE") +
ylab("NEW DENSITY TITLE")
update_labels(p, list(colour="MY NEW LEGEND TITLE")
This will also allow you to change x- and y-axis labels, with separate lines:
update_labels(p, list(x="NEW X LABEL",y="NEW Y LABEL")
I noticed there are two ways to change/specify legend.title for ggboxplot():
library(ggpubr)
bxp.defaultLegend <- ggboxplot(ToothGrowth, x = "dose", y = "len",
color = "dose", palette = "jco")
# Solution 1, setup legend.title directly in ggboxplot()
bxp.legend <- ggboxplot(ToothGrowth, x = "dose", y = "len",
color = "dose", palette = "jco", legend.title="Dose (mg)")
# Solution 2: Change legend title and appearnace in ggboxplot() using labs() and theme() option:
plot1 <- bxp.defaultLegend + labs(color = "Dose (mg)") +
theme(legend.title = element_text(color = "blue", size = 10), legend.text = element_text(color = "red"))
ggarrange(list(bxp.legend, bxp.defaultLegend, plot1), nrow = 1, ncol = 3, common.legend = TRUE)
The code is modified based on the example from GitHub.
Adding this to the mix, for when you have changed the colors. This also worked for me in a qplot with two discrete variables:
p+ scale_fill_manual(values = Main_parties_color, name = "Main Parties")
The way i am going to tell you, will allow you to change the labels of legend, axis, title etc with a single formula and you don't need to use memorise multiple formulas. This will not affect the font style or the design of the labels/ text of titles and axis.
I am giving the complete answer of the question below.
library(ggplot2)
rating <- c(rnorm(200), rnorm(200, mean=.8))
cond <-factor(rep(c("A", "B"), each = 200))
df <- data.frame(cond,rating
)
k<- ggplot(data=df, aes(x=rating, fill=cond))+
geom_density(alpha = .3) +
xlab("NEW RATING TITLE") +
ylab("NEW DENSITY TITLE")
# to change the cond to a different label
k$labels$fill="New Legend Title"
# to change the axis titles
k$labels$y="Y Axis"
k$labels$x="X Axis"
k
I have stored the ggplot output in a variable "k". You can name it anything you like. Later I have used
k$labels$fill ="New Legend Title"
to change the legend. "fill" is used for those labels which shows different colours. If you have labels that shows sizes like 1 point represent 100, other point 200 etc then you can use this code like this-
k$labels$size ="Size of points"
and it will change that label title.
Alas, none of these solutions worked for me. I am working with output from brms::conditional_effects()
My solution required:
+ labs( fill = "New Title", colour = "New Title", labels = "New Title" )
Many people spend a lot of time changing labels, legend labels, titles and the names of the axis because they don't know it is possible to load tables in R that contains spaces " ". You can however do this to save time or reduce the size of your code, by specifying the separators when you load a table that is for example delimited with tabs (or any other separator than default or a single space):
read.table(sep = '\t')
or by using the default loading parameters of the csv format:
read.csv()
This means you can directly keep the name "NEW LEGEND TITLE" as a column name (header) in your original data file to avoid specifying a new legend title in every plot.
The only solution that works with me :
p + guides(fill=guide_legend("New title")

Is it possible to change the default color of the items in scale_size in ggplot2?

I would like to change the default color of the scale_size_manual() in ggplot2 independent of the type of the data in the dataframe.
Is this possible?
For example I would like all of the items in the size legend to be of color "red".
Try this:
> p <- ggplot(mtcars,aes(x = mpg,y = disp,size = cyl)) + geom_point()
> p + scale_size_continuous(guide = guide_legend(override.aes = list(colour = "red")))
Oddly, override.aes seems to not like the American spelling of color. Might have to track that down and submit a small patch...

Adding legend title and main title in ggplot2

Hi I am trying to use ggplot2 to do the following
1) Change the legend name to "asset"
2) Add a title to the top
3) Change the border of each panel to a more solid dark line
4) Would like to change the name and color of each panel chart title "corp" etc
This is what I have and I am not sure how to do this Any help is greatly appreciated
p <- ggplot(mystratcodes, aes(x=annRisk, y = annRet))
p<- p + facet_grid(. ~ sector) + facet_wrap(~sector)
p<- p + geom_point(size=6, aes(color = (mystratcodes$subsector1)))
p<-p+scale_x_continuous(labels = percent, name = "Annualized Risk")
p<-p+scale_y_continuous(labels = percent, name = "Annualized Return")
p<-p+ theme( legend.position = "bottom", legend.key = element_rect(colour = "grey"))
p<-p + scale_colour_manual(values = c("UTIL" = "#fdcc8a", "IND" = "#fc8d59", "FIN" = "#d7301f","ABS" = "#74a9cf", "CMBS" = "#0570b0", "LA" = "#8c96c6", "SOV"= "#88419d", "SUPRA" = "#b3cde3"))
print(p)
Thanks so much
1) You can change the legend name to "Asset" by putting "Asset" as the first parameter in the scale_color_manual function.
scale_colour_manual("Asset",values = ...)
2) You can do
p<-p+labs(title="PUT TITLE HERE")
for the title
3) You can add an additional argument to theme() to change the background color (which will make a border appear around the box)
p<-p+theme(panel.background = element_rect(fill=NA, col="black"))
source: How to place divisions between facet grid lines
You could also try adding p=p+theme_bw() earlier in the expression, but that might change too many things.
4) For the grid labels, you have 2 options (well, more, but these are the easiest). Firstly, you can rename the levels of your data. If you don't want to do that, you can make a labeller function to pass as an argument in facet_grid(). See the example here:
https://stackoverflow.com/a/12104207/1362215
For the color of the panel, you can also use theme() for that
p<-p+theme(strip.background = element_rect(fill = 'purple'))#turns boxes purple

How to change legend title in ggplot

I have the following plot like below. It was created with this command:
library(ggplot2)
df <- data.frame(cond = factor(rep(c("A", "B"), each = 200)),
rating = c(rnorm(200), rnorm(200, mean=.8)))
ggplot(df, aes(x=rating, fill=cond)) +
geom_density(alpha = .3) +
xlab("NEW RATING TITLE") +
ylab("NEW DENSITY TITLE")
Now, I want to modify the legend title from cond into NEW LEGEND TITLE.
So, I just added the following line add the end of the above code:
+labs(colour="NEW LEGEND TITLE")
But it doesn't work. What's the right way to do it?
This should work:
p <- ggplot(df, aes(x=rating, fill=cond)) +
geom_density(alpha=.3) +
xlab("NEW RATING TITLE") +
ylab("NEW DENSITY TITLE")
p <- p + guides(fill=guide_legend(title="New Legend Title"))
(or alternatively)
p + scale_fill_discrete(name = "New Legend Title")
I didn't dig in much into this but because you used fill=cond in ggplot(),
+ labs(color='NEW LEGEND TITLE')
might not have worked. However it you replace color by fill, it works!
+ labs(fill='NEW LEGEND TITLE')
This worked for me in ggplot2_2.1.0
Since you have two densitys I imagine you may be wanting to set your own colours with scale_fill_manual.
If so you can do:
df <- data.frame(x=1:10,group=c(rep("a",5),rep("b",5)))
legend_title <- "OMG My Title"
ggplot(df, aes(x=x, fill=group)) + geom_density(alpha=.3) +
scale_fill_manual(legend_title,values=c("orange","red"))
None of the above code worked for me.
Here's what I found and it worked.
labs(color = "sale year")
You can also give a space between the title and the display by adding \n at the end.
labs(color = 'sale year\n")
Since in your code you used ggplot(data, fill= cond) to create the histogram you need to add the legend title by also using "fill" in the label section i.e. +labs(fill="Title name"). If you were using a different type of plot where the code was ggplot(data, colour= cond), then you could use +labs(colour= "Title Name"). In summary, the lab argument has to match the aes argument.
I have used + guides(fill=guide_legend("my awesome title")) to change the legend title on geom_bar plots but it did not seem to work for geom_point.
There's another very simple answer which can work for some simple graphs.
Just add a call to guide_legend() into your graph.
ggplot(...) + ... + guide_legend(title="my awesome title")
As shown in the very nice ggplot docs.
If that doesn't work, you can more precisely set your guide parameters with a call to guides:
ggplot(...) + ... + guides(fill=guide_legend("my awesome title"))
You can also vary the shape/color/size by specifying these parameters for your call to guides as well.
I am using a facet_wrap in my ggplot and none of the suggested solutions worked for me except ArnaudA's solution:
qplot(…) + guides(color=guide_legend(title="sale year"))
Just to add to the list (the other options here didn't work for me), you can also use the function update_labels for ggplot:
p <- ggplot(df, aes(x=rating, fill=cond)) +
geom_density(alpha=.3) +
xlab("NEW RATING TITLE") +
ylab("NEW DENSITY TITLE")
update_labels(p, list(colour="MY NEW LEGEND TITLE")
This will also allow you to change x- and y-axis labels, with separate lines:
update_labels(p, list(x="NEW X LABEL",y="NEW Y LABEL")
I noticed there are two ways to change/specify legend.title for ggboxplot():
library(ggpubr)
bxp.defaultLegend <- ggboxplot(ToothGrowth, x = "dose", y = "len",
color = "dose", palette = "jco")
# Solution 1, setup legend.title directly in ggboxplot()
bxp.legend <- ggboxplot(ToothGrowth, x = "dose", y = "len",
color = "dose", palette = "jco", legend.title="Dose (mg)")
# Solution 2: Change legend title and appearnace in ggboxplot() using labs() and theme() option:
plot1 <- bxp.defaultLegend + labs(color = "Dose (mg)") +
theme(legend.title = element_text(color = "blue", size = 10), legend.text = element_text(color = "red"))
ggarrange(list(bxp.legend, bxp.defaultLegend, plot1), nrow = 1, ncol = 3, common.legend = TRUE)
The code is modified based on the example from GitHub.
Adding this to the mix, for when you have changed the colors. This also worked for me in a qplot with two discrete variables:
p+ scale_fill_manual(values = Main_parties_color, name = "Main Parties")
The way i am going to tell you, will allow you to change the labels of legend, axis, title etc with a single formula and you don't need to use memorise multiple formulas. This will not affect the font style or the design of the labels/ text of titles and axis.
I am giving the complete answer of the question below.
library(ggplot2)
rating <- c(rnorm(200), rnorm(200, mean=.8))
cond <-factor(rep(c("A", "B"), each = 200))
df <- data.frame(cond,rating
)
k<- ggplot(data=df, aes(x=rating, fill=cond))+
geom_density(alpha = .3) +
xlab("NEW RATING TITLE") +
ylab("NEW DENSITY TITLE")
# to change the cond to a different label
k$labels$fill="New Legend Title"
# to change the axis titles
k$labels$y="Y Axis"
k$labels$x="X Axis"
k
I have stored the ggplot output in a variable "k". You can name it anything you like. Later I have used
k$labels$fill ="New Legend Title"
to change the legend. "fill" is used for those labels which shows different colours. If you have labels that shows sizes like 1 point represent 100, other point 200 etc then you can use this code like this-
k$labels$size ="Size of points"
and it will change that label title.
Alas, none of these solutions worked for me. I am working with output from brms::conditional_effects()
My solution required:
+ labs( fill = "New Title", colour = "New Title", labels = "New Title" )
Many people spend a lot of time changing labels, legend labels, titles and the names of the axis because they don't know it is possible to load tables in R that contains spaces " ". You can however do this to save time or reduce the size of your code, by specifying the separators when you load a table that is for example delimited with tabs (or any other separator than default or a single space):
read.table(sep = '\t')
or by using the default loading parameters of the csv format:
read.csv()
This means you can directly keep the name "NEW LEGEND TITLE" as a column name (header) in your original data file to avoid specifying a new legend title in every plot.
The only solution that works with me :
p + guides(fill=guide_legend("New title")

Resources