gpt4 book ai didi

R 堆积条形图绘制 geom_text

转载 作者:行者123 更新时间:2023-12-02 09:05:32 25 4
gpt4 key购买 nike

我正在尝试使用 ggplot 在 R 中绘制堆积条形图。我还想在该片段的每条条中包含百分比。我尝试关注帖子 1 , 2 , 3但这些值并不完全在各自的 block 中。我的数据是 dropbox 中的一个文件.

我的代码如下:

f<-read.table("Input.txt", sep="\t", header=TRUE)

ggplot(data=f, aes(x=Form, y=Percentage, fill=Position)) +
geom_bar(stat="identity", colour="black") +
geom_text(position="stack", aes(x=Form, y=Percentage, ymax=Percentage, label=Percentage, hjust=0.5)) +
facet_grid(Sample_name ~ Sample_type, scales="free", space="free") +
opts(title = "Input_profile",
axis.text.x = theme_text(angle = 90, hjust = 1, size = 8, colour = "grey50"),
plot.title = theme_text(face="bold", size=11),
axis.title.x = theme_text(face="bold", size=9),
axis.title.y = theme_text(face="bold", size=9, angle=90),
panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank()) +
scale_fill_hue(c=45, l=80)

ggsave("Output.pdf")

输出是-

enter image description here

非常感谢任何帮助。感谢您的帮助和时间!

最佳答案

我认为您使用的是旧版本的ggplot2。因为您的代码已针对 ggplot2 v 0.9.3 进行了修改,所以我得到了以下结果:

p <- ggplot(data = df, aes(x = Form, y = Percentage, fill = Position))
p <- p + geom_bar(stat = "identity", colour = "black")
p <- p + geom_text(position = "stack", aes(x = Form, y = Percentage, ymax = Percentage, label = Percentage, hjust = 0.5))
p <- p + facet_grid(Sample_name ~ Sample_type, scales="free", space="free")
p <- p + theme(plot.title = element_text("Input_profile"),
axis.text.x = element_text(angle = 90, hjust = 1, size = 8, colour = "grey50"),
plot.title = element_text(face="bold", size=11),
axis.title.x = element_text(face="bold", size=9),
axis.title.y = element_text(face="bold", size=9, angle=90),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
p <- p + scale_fill_hue(c=45, l=80)
p

ggplot2_text_placement

您会看到文本对象通常放置正确。有些地方的条形太短,导致数字重叠。您还可以使用 size 参数。

要纠正这个问题,您可以执行类似的操作来自己将数字相加。

df <- ddply(df, .(Form, Sample_type, Sample_name), transform, 
cum.perc = Reduce('+', list(Percentage/2,cumsum(c(0,head(Percentage,-1))))))

p <- ggplot(data = df, aes(x = Form, y = Percentage, fill = Position))
p <- p + geom_bar(stat = "identity", colour = "black")
p <- p + geom_text(aes(x = Form, y = cum.perc, ymax = cum.perc, label = Percentage, hjust = 0.5), size=2.7)
p <- p + facet_grid(Sample_name ~ Sample_type, scales="free", space="free")
p <- p + theme(plot.title = element_text("Input_profile"),
axis.text.x = element_text(angle = 90, hjust = 1, size = 8, colour = "grey50"),
plot.title = element_text(face="bold", size=11),
axis.title.x = element_text(face="bold", size=9),
axis.title.y = element_text(face="bold", size=9, angle=90),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
p <- p + scale_fill_hue(c=45, l=80)
p

这给出:

ggplot2_facet_text_final

关于R 堆积条形图绘制 geom_text,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14941940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com