简体   繁体   中英

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: 情节

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: 空地

So how do I remove the legend from my plot?

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.

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)

没有传说的情节

尝试一下:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM