当前位置: 动力学知识库 > 问答 > 编程问答 >

r - 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)

网友答案:

Just try this:

p + geom_point(aes(colour = factor(clustering)),show.legend=FALSE)
分享给朋友:
您可能感兴趣的文章:
随机阅读: