【问题标题】:Why is ggplot2 histogram behavior different when the x/y-axes have different types?当 x/y 轴具有不同类型时,为什么 ggplot2 直方图行为不同?
【发布时间】:2014-10-27 02:41:01
【问题描述】:

顶部的直方图是价格的密度直方图,底部的直方图是克拉的密度(钻石数据集)。

ggplot(diamonds,aes(x=price, fill=color)) +
    geom_histogram(aes(y=..density..)) +
    theme(legend.position="none") +
    theme(axis.title.x=element_blank(), axis.title.y=element_blank())

ggplot(diamonds,aes(x=carat, fill=color)) + 
    geom_histogram(aes(y =..density..)) +
    theme(legend.position = "none") +
    theme(axis.title.x=element_blank(), axis.title.y=element_blank())

为什么上面两张图不一样?怎么做?谢谢!

【问题讨论】:

  • 这实际上是一个合法的问题,不应关闭。看我的回答。
  • 我不明白这里应该与哪个差异相关,是 y 轴上的值吗? @stata,您能否尝试进一步解释,或者尝试上传更好版本的情节图像?
  • 将绘图导出为 png 或 jpeg 格式的两个单独的图像文件(如果您使用 RStudio,这很容易)应该会更好
  • @Marius 我想用上面的 R 代码来绘制上面相同的图片,但现在我不能。

标签: r ggplot2 histogram


【解决方案1】:

ggplot 图会根据美学中变量的类型(x、y、填充等)尝试智能地表现。但默认值并不总是正确的。

在这种情况下,您的 x 轴有不同的类型:price 是整数,而 carat 是数字。 如果要覆盖默认行为,只需使用 as.numeric/ as.integer/ as.factor/ 等:

ggplot(... aes(x=as.numeric(price), ...

对于价格(整数),默认统计是 stat="bin"。所以你会得到堆叠的直方图。

对于克拉(数字),它是连续的。有关详细信息,请参阅文档。

【讨论】:

  • 使用 as.numeric/ as.integer/ as.factor/ 等无法绘制上面两张图一样的图,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-11
  • 2018-11-14
  • 2019-07-08
  • 2022-01-24
  • 1970-01-01
相关资源
最近更新 更多