问题描述
我创建了一个具有这种性质的数据的堆积直方图:
> haps
tot K7a
1 1 2
2 7 1
3 1 4
4 8 3
5 1 6
tot是每个元素的观察计数(我在上表中仅显示1899年的5个元素), K7a是具有7个水平的因子。 数据应该被读取,例如例如:元素1被观察到一次并属于第2组,...元素4被观察到8次并属于第3组,依此类推。
使用以下代码,我得到了B&W的直方图:
ggplot(haps,aes(x=tot) +
geom_histogram(binwidth = 0.5) +
scale_y_continuous(trans="log1p",breaks = c(1,2,3,4,5,10,15,20,25,50,100,500,1000,1500,2000)) +
scale_x_continuous(limits = c(0,20),breaks = c(0,6,8,12,14,16,18,20))+
theme_gray(base_size = 10) + labs(x = "Haplotype repeats",y = "Number of events" )
然后我想为7组添加颜色,我使用以下代码,只需将填充添加到aes:
ggplot(haps,aes(x=tot,fill=K7a)) +
geom_histogram(binwidth = 0.5) +
scale_y_continuous(trans="log1p",2000)) +
(limits = c(0,20))+
theme_gray(base_size = 10) + labs(x = "Haplotype repeats",y = "Number of events" )
即使我使用相同的代码,第二张图也会改变y比例尺,我无法弄清楚如何获得与黑白图中相同比例尺的图。
解决方法
不太确定发生了什么。我最好的猜测是该转换仅适用于y
标度,而不适用于fill
标度。
在使用coord_trans()
完成所有计算之后,您可以“解决”此问题并应用转换:
library(ggplot2)
df <- read.table(text="
tot K7a
1 1 2
2 7 1
3 1 4
4 8 3
5 1 6")
ggplot(df,aes(tot,fill = factor(K7a))) +
scale_y_continuous( breaks = c(1,2,3,4,5,10,15,20,25,50,100,500,1000,1500,2000)) +
geom_histogram(binwidth = 1) +
coord_trans(y = 'log1p')
由reprex package(v0.3.0)于2020-10-18创建