简体   繁体   English

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

[英]Change y-axis of dot plot to reflect actual count using geom_dotplot

I am trying to create a dot plot using geom_dotplot of ggplot2 .我正在尝试使用geom_dotplotggplot2创建一个点图。

However, as shown in the examples on this page , the scales of y-axis range from 0 to 1. I wonder how I can change the y-axis scale so the values reflect the actual count of the data.但是,如本页示例中所示,y 轴的刻度范围从 0 到 1。我想知道如何更改 y 轴刻度,使值反映数据的实际计数。

Here is an example which might be helpful.这是一个可能有帮助的例子。

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

15 个虹膜花瓣长度的点图

I don't know why it works.我不知道为什么它有效。 It seems that the height of y axis for geom_dotplot is 1. The ratio between x and y was setup by coor_fixed(ratio=binwidth * dotsize * max frequency). geom_dotplot 的 y 轴高度似乎为 1。x 和 y 之间的比率由 coor_fixed(ratio=binwidth * dotsize * max frequency) 设置。

I would recommend you to use geom_histogram instead.我建议您改用geom_histogram

library(ggplot2)
ggplot(mtcars, aes(x = mpg)) + 
  geom_histogram(binwidth=1)

The issue seem to be in that geom_dotplot cannot be converted to count, as seen in the github issue here .问题似乎在于geom_dotplot无法转换为计数,如 github issue here中所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM