【问题标题】:How to change the x-axis scale如何更改 x 轴刻度
【发布时间】:2019-06-26 15:19:12
【问题描述】:

enter image description here我为泊松分布生成了 1000 组随机数据,并将所有数据绘制成概率分布图。我想将 x 轴刻度更改为每个单位 2,例如 0、2、4、6、8、10 ....我已经设置了 x 轴的最大值和最小值,但它没有显示我的值期待

set.seed(124)

Sample1000 <- replicate(1000, matrix(data=rpois(100, lambda = 3),ncol = 1), simplify = TRUE)
Graph1000 <- gather(as.data.frame(Sample1000))
View(Sample1000)
colMeans(Sample1000)
apply(Sample1000, 2, var)

ggplot(Graph1000, aes(x = value)) +
  geom_density(aes(group = key)) +
  labs(x = "y", y = "P(y)", title = "Probability density function for 1000 sample") +
  theme_classic() +
  theme(plot.title = element_text(hjust = 0.5)) +
  scale_x_continuous(expand = c(0,0), limits = c(0,14))  +
  scale_y_continuous(expand = c(0,0))

【问题讨论】:

  • 添加一个覆盖数据范围的breaks 参数。例如scale_x_continuous(expand=c(0,0), breaks=seq(0, 20, 2))。如果要设置小于数据范围的限制,请使用coord_cartesian(xlim=c(0,14))。在scale_x_continuous 内设置限制将排除任何计算(例如核密度估计)限制之外的数据。
  • 更多关于coord_cartesianscale_x/y_continuoussee here的信息。
  • 但我从随机生成中得到的最大数字是 12,所以这就是为什么我将 scale_x_continuous 的限制设置为 (0,14)

标签: r


【解决方案1】:

您可以在scale_x_continuous() 上设置breaks
这是产生你的情节的代码:

ggplot(Graph1000, aes(x = value)) +
  geom_density(aes(group = key)) +
  labs(x = "y", y = "P(y)", title = "Probability density function for 1000 sample") +
  theme_classic() +
  theme(plot.title = element_text(hjust = 0.5)) +
  #Set breaks on x axis
  scale_x_continuous(breaks = seq(from = 0,to = 14,by = 2), limits = c(0,14))  +
  scale_y_continuous(expand = c(0,0))

【讨论】: