使用 geom_dotplot 更改点图的 y 轴以反映实际计数

Jun*_*ang 6 r ggplot2

我正在尝试使用geom_dotplotof创建点图ggplot2

但是,如本页示例中所示,y 轴的刻度范围从 0 到 1。我想知道如何更改 y 轴刻度,以便这些值反映数据的实际计数。

Fei*_* YE 5

这是一个可能有帮助的示例。

library(ggplot2)
library(ggExtra)
library(dplyr)

# use the preloaded iris package in R
irisdot <- head(iris["Petal.Length"],15)
# find the max frequency (used `dplyr` package). Here n is the label for frequency returned by count().
yheight <- max(dplyr::count(irisdot, Petal.Length)["n"]) 
# basic dotplot (binwidth = the accuracy of the data)
dotchart = ggplot(irisdot, aes(x=Petal.Length), dpi = 600)
binwidth = 0.1
dotsize = 1
dotchart = dotchart + geom_dotplot(binwidth=binwidth, method="histodot", dotsize = dotsize, fill="blue")
# use coor_fixed(ratio=binwidth*dotsize*max frequency) to setup the right y axis height.
dotchart = dotchart + 
  theme_bw() + 
  coord_fixed(ratio=binwidth*dotsize*yheight)
# tweak the theme a little bit
dotchart = dotchart + theme(panel.background=element_blank(),
                            panel.border = element_blank(),
                            panel.grid.minor = element_blank(),
                            # plot.margin=unit(c(-4,0,-4,0), "cm"),
                            axis.line = element_line(colour = "black"),
                            axis.line.y = element_blank(),
)
# add more tick mark on x axis
dotchart = dotchart + scale_x_continuous(breaks = seq(1,1.8,0.1))
# add tick mark on y axis to reflect frequencies. Note yheight is max frequency.
dotchart = dotchart + scale_y_continuous(limits=c(0, 1), expand = c(0, 0), breaks = seq(0, 1,1/yheight), labels=seq(0,yheight))
# remove x y lables and remove vertical grid lines
dotchart = dotchart + labs(x=NULL, y=NULL) + removeGridX()
dotchart
Run Code Online (Sandbox Code Playgroud)

15 个鸢尾花瓣长度的点图

我不知道为什么它有效。看起来geom_dotplot的y轴高度是1。x和y之间的比率是通过coor_fixed设置的(ratio=binwidth *dotsize *最大频率)。


nad*_*zan 1

我建议您使用geom_histogram它。

library(ggplot2)
ggplot(mtcars, aes(x = mpg)) + 
  geom_histogram(binwidth=1)
Run Code Online (Sandbox Code Playgroud)

问题似乎在于geom_dotplot无法转换为计数,如 github 问题中所示