【问题标题】:What does the error stat_count() reference in a ggplot visualization?ggplot 可视化中的错误 stat_count() 引用什么?
【发布时间】:2017-12-13 17:13:19
【问题描述】:

错误 stat_count() 在 ggplot 可视化中引用什么?

例如,我有以下数据框。

x <- c(1,2,3)
y <- c(1,2,3)
df <- data.frame(x,y)

接下来,我使用 ggplot 和 geom_bar() 绘制它。

ggplot(df, aes(x, y)) + 
  geom_bar() + 
  xlab("x") + 
  ylab("y") + 
  ggtitle("x and y")

我得到错误:

错误:stat_count() 不得与 y 美学一起使用。

错误stat_count() 在 ggplot 可视化中引用了什么,如何解决它以制作成功的条形图?

谢谢!

【问题讨论】:

  • 使用geom_bar(stat = "identity")。所以stat_count()函数使用aes()中给出的y变量。

标签: r ggplot2 geom-bar


【解决方案1】:

绘制具有指定y 值的条的正确几何图形是geom_col()

x <- c(1,2,3)
y <- c(1,2,3)
df <- data.frame(x,y)

ggplot(df, aes(x, y)) + 
  geom_col() + 
  xlab("x") + 
  ylab("y") + 
  ggtitle("x and y")

您使用的几何图形geom_bar() 想要通过调用stat_count() 来计算条形的高度。而stat_count() 不采用y 美学,因为它会计算自己的y 值。

如果我们想使用geom_bar(),但不希望它进行任何计数,我们必须通过设置stat="identity"(然后调用stat_identity()而不是stat_count())来明确告诉它:

ggplot(df, aes(x, y)) + 
  geom_bar(stat="identity") + 
  xlab("x") + 
  ylab("y") + 
  ggtitle("x and y")

但是,现在不鼓励这种方法。

【讨论】:

    猜你喜欢
    • 2015-08-13
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多