【问题标题】:How to put histogram with ggplot in the beginning of axes (0,0)?如何将带有ggplot的直方图放在轴(0,0)的开头?
【发布时间】:2018-09-30 11:06:37
【问题描述】:

我想创建一个直方图,但我无法将它放在轴 (0,0) 的开头。目前它向右移动,看起来不太好。我期望 expand_limits(x = 0, y = 0) 来解决这个问题。我知道它可能已经得到了回答,但我发现的所有解决方案都不起作用。如果您指出问题出在哪里,谢谢。这是我的代码:

ggplot(data=dataset, aes(x= dataset$count)) + 
        geom_histogram(binwidth = 3,
                       col="blue", 
                       fill="darkblue") + 
        labs(title="Retweets Distribution") +
        labs(x="Retweet number") +
        theme(plot.title = element_text(hjust = 0.5)) +
        scale_x_continuous(limits = c(0,250)) +
        scale_y_continuous(limits = c(0,250)) + expand_limits(x = 0, y = 0)

还有剧情:

还有count列的总结:

【问题讨论】:

  • 根据您提供的信息,count 似乎没有小于 24 的值。
  • 我同意@jdobres。你能提供dataset的sn-p吗?
  • @jdobres 我正在考虑它,但是有很多接近 0 的值。我尝试了table(dataset$count),它向我展示了摘要
  • 我也同意@jdobres。你应该检查count variables 的分布。 summary(dataset$count)
  • 奇怪。 . .一件事是,如果您为ggplot() 指定data 参数,您可以只使用变量名:aes(x = count)

标签: r ggplot2 histogram axes


【解决方案1】:

绘图将在绘图区域的边缘之间自动填充。因此,即使您将轴设置为从 0 开始,绘图区域和边距之间也会有空间。

由于您没有提供数据集,这里有一个关于如何修复它的可重现示例。您可以更改 scale_x_continuous 内的 expand 选项以删除此填充:

ggplot(diamonds, aes(carat)) +
  geom_histogram() +
  scale_x_continuous(expand = c(0,0))

在你的情况下,你将不得不使用scale_x_continuous(limits = c(0,250), expand=c(0,0))

如果您希望将整个图表左移,只需更改限制即可。 例如

scale_x_continuous(limits = c(20,250), expand=c(0,0))

查看包文档了解更多详情:http://ggplot2.tidyverse.org/reference/scale_continuous.html

【讨论】:

  • 谢谢,但没有帮助。但是,我尝试使用较小的子集并且效果很好。
猜你喜欢
  • 2020-11-21
  • 1970-01-01
  • 2011-01-25
  • 1970-01-01
  • 2016-10-17
  • 1970-01-01
  • 2022-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多