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

问题描述 投票:1回答:2

我试图创建一个使用geom_dotplotggplot2点图。

然而,如图中上this page的例子中,y轴的范围从0到1的刻度我不知道如何可以改变y轴刻度所以值反映了数据的实际计数。

r ggplot2
2个回答
1
投票

下面是这可能是有帮助的一个例子。

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)
dotchart = dotchart + geom_dotplot(binwidth=0.1, method="histodot", dotsize = 1, fill="blue")
# use coor_fixed(ratio=binwidth*dotsize*max frequency) to setup the right y axis height.
dotchart = dotchart + theme_bw() + coord_fixed(ratio=0.1*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

A dotplot for 15 iris petal lengths

我不知道为什么它的工作原理。似乎y轴的用于geom_dotplot高度为1. coord_fixed(比率=箱宽度* dotsize *最大频率)的x和y是设置之间的比值。


0
投票

我建议你改用geom_histogram

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

这个问题似乎是在geom_dotplot不能转换来算,在GitHub的问题here看到。

© www.soinside.com 2019 - 2024. All rights reserved.