I'm trying to remove the title of a legend in ggplot2:
df <- data.frame(
g = rep(letters[1:2], 5),
x = rnorm(10),
y = rnorm(10)
)
library(ggplot2)
ggplot(df, aes(x, y, colour=g)) +
geom_line(stat="identity") +
theme(legend.position="bottom")
I've seen this question and none of the solutions there seem to work for me. Most give an error about how opts is deprecated and to use theme instead. I've also tried various versions of theme(legend.title=NULL), theme(legend.title=""), theme(legend.title=element_blank), etc. Typical error messages are:
'opts' is deprecated. Use 'theme' instead. (Deprecated; last used in version 0.9.1)
'theme_blank' is deprecated. Use 'element_blank' instead. (Deprecated; last used in version 0.9.1)
I'm using ggplot2 for the first time since version 0.9.3 was released and I'm finding it difficult to navigate some of the changes...
You were almost there : just add theme(legend.title=element_blank())
ggplot(df, aes(x, y, colour=g)) +
geom_line(stat="identity") +
theme(legend.position="bottom") +
theme(legend.title=element_blank())
This page on Cookbook for R gives plenty of details on how to customize legends.
This works too and also demonstrates how to change the legend title:
ggplot(df, aes(x, y, colour=g)) +
geom_line(stat="identity") +
theme(legend.position="bottom") +
scale_color_discrete(name="")
Another option using labs and setting colour to NULL.
ggplot(df, aes(x, y, colour = g)) +
geom_line(stat = "identity") +
theme(legend.position = "bottom") +
labs(colour = NULL)
Since you may have more than one legends in a plot, a way to selectively remove just one of the titles without leaving an empty space is to set the name argument of the scale_ function to NULL, i.e.
scale_fill_discrete(name = NULL)
(kudos to #pascal for a comment on another thread)
For Error: 'opts' is deprecated. Use theme() instead. (Defunct; last used in version 0.9.1)'
I replaced opts(title = "Boxplot - Candidate's Tweet Scores") with
labs(title = "Boxplot - Candidate's Tweet Scores"). It worked!
Related
I'm trying to learn about animating plots with gganimate, and I'm wondering if someone has a tip for the problems I'm running into. In an effort to make things simple, I'm doing this by creating a new project in RStudio Cloud, installing the ggplot2, gganimate, and datasauRus packages, and following this example from Isaac Faber:
library(datasauRus)
library(ggplot2)
library(gganimate)
ggplot(datasaurus_dozen, aes(x=x,y=y)) +
geom_point() +
theme_minimal() +
transition_states(dataset,3,1) +
ease_aes()
This creates a series of .PNG files but I cannot see an animation. Some seem to suggest that I can see it using the "print" function, but this does not work either.
I have also been unable to export this as a .GIF, although I have followed the advice given here. Specifically, the magick packages does not work for me (I get the same error about my images not being magick image objects), and when I try the following code:
p <- ggplot(datasaurus_dozen, aes(x=x,y=y)) +
geom_point() +
theme_minimal() +
transition_states(dataset,3,1) +
ease_aes()
anim <- animate(p)
anim_save("myfilename.gif",anim)
R tells me that The
animation object does not specify a save_animation method.
I've been unable to find examples or documentation that tells me how to specify a save_animation method. If anyone has advice on this topic, it would be greatly appreciated!
you're doing one step too many:
library(datasauRus)
library(ggplot2)
library(gganimate)
p <- ggplot(datasaurus_dozen, aes(x=x,y=y)) +
geom_point() +
theme_minimal() +
transition_states(dataset,3,1) +
ease_aes()
anim_save("myfilename.gif",p)
I solved this by specifying the gifski_renderer() in animate():
library(tidyverse)
library(gganimate)
library(gapminder)
g <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
geom_point(alpha = 0.7, show.legend = FALSE) +
scale_colour_manual(values = country_colors) +
scale_size(range = c(2, 12)) +
scale_x_log10() +
facet_wrap(~continent) +
# Here comes the gganimate specific bits
labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') +
transition_time(year) +
ease_aes('linear')
animate(g, height=400, width=600, renderer=gifski_renderer())
anim_save("gapminder.gif", g)
Note: this is the default renderer for animate(), but somehow needed to be specified explicitly. After doing it the first time, I no longer need to set it, a behavior I can't explain.
I'm a newbie, so this might be super basic.
When I run this code
Dplot <- qplot(x = diamonds$carat, y = diamonds$price, color = diamonds$color) +
ggtitle("An A+ plot") +
xlab("carat") +
ylab("price") +
geom_point()
Dplot <- Dplot + facet_wrap(vars(diamonds$clarity))
Dplot
I get an error message that says:
Error in gList(list(x = 0.5, y = 0.5, width = 1, height = 1, just =
"centre", :
only 'grobs' allowed in "gList"
I've tried googling, but haven't been able to figure out what the issue is.
I would advise against using qplot except in the most basic cases. It teaches bad habits (like using $) that should be avoided in ggplot.
We can make the switch by passing the data frame diamonds to ggplot(), and putting the mappings inside aes() with just column names, not diamonds$. Then the facet_wrap works fine as long as we also omit the diamonds$:
Dplot = ggplot(diamonds, aes(x = carat, y = price, color = color)) +
ggtitle("An A+ plot") +
xlab("carat") +
ylab("price") +
geom_point()
Dplot + facet_wrap(vars(clarity))
Dplot + facet_wrap(~ clarity) # another option
Notice the code is actually shorter because we don't need to type diamonds$ all the time!
The vars(clarity) option works fine, more traditionally you would see formula interface used ~ clarity. The vars() option is new-ish, and will play a little nicer if you are writing a function where the name of a column to facet by is stored in a variable.
The following code works like a charm:
foo = data.frame(x=c(1,2,3),
y=c(4,5,6),
lt=c('dotted', 'dashed', 'dotdash'))
ggplot(foo, aes(x,y)) + geom_point() +
geom_vline(aes(xintercept=x, linetype=lt))
The following code drops linetype. Why?
ggplot(foo, aes(x,y)) + geom_point() +
geom_vline(xintercept=3, aes(linetype=lt)) +
facet_wrap(~lt)
I am using ggplot 0.9.3.1 in Rstudio.
I can confirm your problem and also that Sandy's comment fixes it for me, using ggplot2 1.0 in R 3.1.2:
geom_vline(aes(xintercept = 3, linetype = lt))
However I still think this is a bug in (maybe just the documentation for) geom_vline. I think xintercept should be listed as a required aesthetic with a default value of 0. Notably, the code below "works" -- the lines have the correct hashing at the default x location of 0:
ggplot(foo, aes(x,y)) +
geom_point() +
geom_vline(aes(linetype=lt)) +
facet_wrap(~lt)
So the problem seems to be that when required aesthetics are supplied outside of aes(), the arguments inside of aes() are ignored. This is different than other functions. For example,
ggplot(foo) + geom_point(x=1, aes(y=y))
gives an error but
ggplot(foo) + geom_point(aes(x=1, y=y))
does not. As far as I'm concerned, ideal behavior would be for geom_vline() to behave the same way as geom_point() in this regard.
I have a question concerning the legend in ggplot2.
Say I have a hypothetical dataset about mean carrot length for two different colours at two farms:
carrots<-NULL
carrots$Farm<-rep(c("X","Y"),2)
carrots$Type<-rep(c("Orange","Purple"),each=2)
carrots$MeanLength<-c(10,6,4,2)
carrots<-data.frame(carrots)
I make a simple bar plot:
require(ggplot2)
p<-ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top")
p
My question is: is there a way to remove the title ('Type') from the legend?
Thanks!
I found that the best option is to use + theme(legend.title = element_blank()) as user "gkcn" noted.
For me (on 03/26/15) using the previously suggested labs(fill="") and scale_fill_discrete("") remove one title, only to add in another legend, which is not useful.
You can modify the legend title by passing it as the first parameter to a scale. For example:
ggplot(carrots, aes(y=MeanLength, x=Farm, fill=Type)) +
geom_bar(position="dodge") +
theme(legend.position="top", legend.direction="horizontal") +
scale_fill_discrete("")
There is also a shortcut for this, i.e. labs(fill="")
Since your legend is at the top of the chart, you may also wish to modify the legend orientation. You can do this using opts(legend.direction="horizontal").
You can use labs:
p + labs(fill="")
The only way worked for me was using legend.title = theme_blank() and I think it is the most convenient variant in comparison to labs(fill="") and scale_fill_discrete(""), which also could be useful in some cases.
ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(
legend.position="top",
legend.direction="horizontal",
legend.title = theme_blank()
)
P.S. There are more useful options in documentation.
You've got two good options already, so here's another using scale_fill_manual(). Note this also lets you specify the colors of the bars easily:
ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top") +
scale_fill_manual(name = "", values = c("Orange" = "orange", "Purple" = "purple"))
If you are using the up-to-date (As of January 2015) version of ggplot2 (version 1.0), then the following should work:
ggplot(carrots, aes(y = MeanLength, x = Farm, fill = Type)) +
geom_bar(stat = "identity", position = "dodge") +
theme(legend.position="top") +
scale_fill_manual(name = "", values = c("Orange" = "orange", "Purple" = "purple"))
#pascal 's solution in a comment to set the name argument of a scale function, such as scale_fill_discrete, to NULL, is the best option for me. It allows removing the title together with the blank space that would remain if you used "", while at the same time allowing the user to selectively remove titles, which is not possible with the theme(legend.title = element_blank()) approach.
Since it is buried in a comment, I am posting it as an answer to potentially increase its visibility, with kudos to #pascal.
TL;DR (for the copy-pasters):
scale_fill_discrete(name = NULL)
I am working on finishing up a graph generated using ggplot2 like so...
ggplot(timeSeries, aes(x=Date, y=Unique.Visitors, colour=Revenue))
+ geom_point() + stat_smooth() + scale_y_continuous(formatter=comma)
I have attached the result and you can see the numeric values in the legend for Revenue do not have a comma. How can I add a comma to those values? I was able to use scale_y_continuous for the axis, can that be used for the legend also?
Just to keep current, in ggplot2_0.9.3 the working syntax is:
require(scales)
ggplot(timeSeries, aes(x=Date, y=Unique.Visitors, colour=Revenue)) +
geom_point() +
stat_smooth() +
scale_y_continuous(labels=comma) +
scale_colour_continuous(labels=comma)
Also see this exchange
Note 2014-07-16: the syntax in this answer has been obsolete for some time. Use metasequoia's answer!
Yep - just a matter of getting the right scale_colour_ layer figured out. Try:
ggplot(timeSeries, aes(x = Date, y = Unique.Visitors, colour = Revenue)) +
geom_point() +
stat_smooth() +
scale_y_continuous(formatter = comma) +
scale_colour_continuous(formatter = comma)
I personally would also move my the colour mapping to the geom_point layer, so that it doesn't give you that odd line behind the dot in the legend:
ggplot(timeSeries, aes(x = Date, y = Unique.Visitors)) +
geom_point(aes(colour = Revenue)) +
stat_smooth() +
scale_y_continuous(formatter = comma) +
scale_colour_continuous(formatter = comma)
...as I stumbled over this older thread, maybe it makes sense to add you need to load library("scales"), otherwise you get the following error message
Error in check_breaks_labels(breaks, labels) : object 'comma' not found