【问题标题】:Removing ggplot2 legend removes whole data from the plot删除 ggplot2 图例会从图中删除整个数据
【发布时间】:2016-12-03 04:30:56
【问题描述】:

这里我有二维数字数组dataset 和数字一维标签数组clustring。然后我用以下代码绘制它:

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

显示精美图片:

现在我想完全删除图例,所以here我找到了可能的解决方案:

# 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")

但是这些命令都无济于事。它显示的是空图:

那么如何从我的情节中删除图例?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    试试这个:

    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
    

    在您的代码中,您不会在每次向其中添加内容后再次保存该图。您可以通过更改添加到绘图的线条来解决此问题:

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

    但我写的方式是更常见的R格式。

    【讨论】:

      【解决方案2】:

      geom_point 中使用show.legend = FALSE。这是一个使用 ggplot2 的 diamonds 数据集的示例。

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

      【讨论】:

      • 它说:警告:忽略未知的美学:show.legend
      【解决方案3】:

      试试这个:

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

      【讨论】:

      • 它说:警告:忽略未知的美学:show.legend
      • 是的,没错。 Show.legend 是一个 geom_point 参数。请检查 show.legend 参数前右括号的正确数量。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2012-07-27
      相关资源
      最近更新 更多