在点图上显示x轴的计数

时间:2016-08-11 15:26:27

标签: r ggplot2

我希望有一个点图,显示x轴上的计数。你怎么能得到下面的dotplot来显示x-asix的计数?

谢谢。

    date = seq(as.Date("2016/1/5"), as.Date("2016/1/11"), "day")
    value = c(11,11,12,12,13,14,14)
    dat =data.frame(date = date, value = value)
    dat
    library(ggplot2)
    library(ggplot2)
ggplot(dat, aes(x = value)) + geom_dotplot(binwidth = .8) +
  scale_y_discrete(breaks= seq(1,max(table(dat$value))+2,1), 
                   labels = seq(1,max(table(dat$value))+2,1) ) #tried using scale_y discrete but it does nothing

2 个答案:

答案 0 :(得分:2)

ylim(0, A)给出你想要的东西,其中A是计算1.00密度所需的堆叠点数。我们可以计算A的精确值(但有点复杂;对话方法给出近似值)。 (我参考了post1post2post3

library(ggplot2); library(grid)

date = seq(as.Date("2016/1/5"), as.Date("2016/1/12"), "day")
value = c(11,11,12,12,13,14,14,14)
dat =data.frame(date = date, value = value)

### base plot
g <- ggplot(dat, aes(x = value)) + geom_dotplot(binwidth = 0.8) + coord_flip()
g  # output to read parameter

### calculation of width and height of panel
grid.ls(view=TRUE,grob=FALSE)
seekViewport('panel.3-4-3-4')
real_width <- convertWidth(unit(1,'npc'), 'inch', TRUE)
real_height <- convertHeight(unit(1,'npc'), 'inch', TRUE)

### calculation of other values
height_coordinate_range <- diff(ggplot_build(g)$panel$ranges[[1]]$y.range)
real_binwidth <- real_height / height_coordinate_range * 0.8  # 0.8 is the argument binwidth
num_balls <- real_width / 1.1 / real_binwidth  # the number of stacked balls. 1.1 is expanding value.

g + ylim(0, num_balls)

# The dirty balls border probably comes from my environment. 

enter image description here

答案 1 :(得分:0)

您可以添加coord_flip()来切换ggplot中的x和y轴。以下是您的脚本示例:

date = seq(as.Date("2016/1/5"), as.Date("2016/1/11"), "day")
    value = c(11,11,12,12,13,14,14)
    dat =data.frame(date = date, value = value)
dat

编辑,依靠x轴:

这将给出带有简化命令的点图,并将计数作为x轴上的标签。注意:binwidth已从0.8更改为1,以适应ylim的使用而不是比例。

library(ggplot2)
   ggplot(dat, aes(x = value)) +
    geom_dotplot(binwidth = 1) +
    coord_flip() +
    ylim(0,max(table(dat$value))+2)

编辑,依靠y轴:

library(ggplot2)
   ggplot(dat, aes(x = value)) +
    geom_dotplot(binwidth = 1) +
    ylim(0,max(table(dat$value))+2)

enter image description here

相关问题