showing count on x-axis for dot plot

2019-08-22 13:17发布

问题:

I'd like to have a dot plot that shows the count on the x-axis. How can you get the dotplot below to show the count on the x-asix?

Thank you.

    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

回答1:

ylim(0, A) gives what you want, where A is the number of stacked dots necessary to count 1.00 density. We can calculate the exact value of A (but a little complexly ; Dialogical approach gives you approximate value). (I reffered to post1, post2, and post3)

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. 



回答2:

You can add coord_flip() to switch the x and y axes in ggplot. Here's an example with your script:

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

Edit, count on x-axis:

This will give a dotplot with simplified commands, and the counts as labels on the x-axis. Note: The binwidth has been changed from 0.8 to 1 to accommodate the use of ylim rather than scales.

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

Edit, count on y-axis:

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



标签: r ggplot2