Aeteros
Aeteros

Reputation: 673

Removing ggplot2 legend removes whole data from the plot

Here I have 2-dim numeric array dataset and numeric 1-dim array of labels clustring. Then I plot it with the following code:

  s = data.frame(x = dataset[,1], y = dataset[,2])
  p = ggplot(s, aes(x, y))
  p + geom_point(aes(colour = factor(clustering)))

which displays beautiful picture: plot

Now I want to remove legend completely, so here I've found possible solution:

# Remove legend for a particular aesthetic (fill)
p + guides(fill=FALSE)

# It can also be done when specifying the scale
p + scale_fill_discrete(guide=FALSE)

# This removes all legends
p + theme(legend.position="none")

but none of such commands wont help. It shows empty plot instead: empty plot

So how do I remove the legend from my plot?

Upvotes: 0

Views: 1313

Answers (3)

jvb
jvb

Reputation: 61

Just try this:

p + geom_point(aes(colour = factor(clustering)),show.legend=FALSE)

Upvotes: 2

hoggue
hoggue

Reputation: 147

Use show.legend = FALSE within geom_point. Here is an example using ggplot2's diamonds dataset.

s <- diamonds
p <- ggplot(data = s, aes(x = depth, y = price))
p + geom_point(aes(colour = factor(cut)), show.legend = FALSE)

plot with no legend

Upvotes: 2

calico_
calico_

Reputation: 1221

Try this:

library(ggplot2)

s = data.frame(x = rnorm(20), y = rnorm(20), clustering = rep(c(1, 2), 10))

p <- ggplot(s, aes(x, y))+
  guides(fill=FALSE)+
  geom_point(aes(colour = factor(clustering)))+
  scale_fill_discrete(guide=FALSE)+
  theme(legend.position="none")
p

In your code, you are not saving the plot again after each time you add something to it. You can fix this by changing the lines that add to the plot:

# Remove legend for a particular aesthetic (fill)
p = p + guides(fill=FALSE)

But the way I wrote is is more common R formatting.

Upvotes: 2

Related Questions