我是 R 和 ggplot2 的新手。我对此进行了很多搜索,但找不到解决方案。
Sample observation1 observation2 observation3 percentage
sample1_A 163453473 131232689 61984186 30.6236955883
Sample1_B 170151351 137202212 59242536 26.8866816109
sample2_A 194102849 162112484 89158170 40.4183031852
sample2_B 170642240 141888123 79925652 41.7493687378
sample3_A 192858504 161227348 90532447 41.8068248626
sample3_B 177174787 147412720 81523935 40.5463120438
sample4_A 199232380 174656081 118115358 55.6409038531
sample4_B 211128931 186848929 123552556 54.7201927527
sample5_A 186039420 152618196 87012356 40.9656544833
sample5_B 145855252 118225865 66265976 39.5744515254
sample6_A 211165202 186625116 112710053 48.5457722338
sample6_B 220522502 193191927 114882014 47.238670909
我计划使用 ggplot2 绘制条形图。我想将前三列绘制为条形图“闪避”,并用百分比标记 observation3
条形图。我可以如下绘制条形图,但无法使用 geom_text()
添加标签。
data1 <- read.table("readStats.txt", header=T)
data1.long <- melt(data1)
ggplot(data1.long[1:36,], aes(data1.long$Sample[1:36],y=data1.long$value[1:36], fill=data1.long$variable[1:36])) + geom_bar(stat="identity", width=0.5, position="dodge")
最佳答案
将 data1
转换为长格式,其中观察列作为度量变量,Sample
和 percentage
列作为 id 变量。计算用于放置百分比的最大值 mx
。然后执行剧情。请注意,geom_bar
使用 data1.long
,但 geom_text
使用 data1
。 我们为百分比文本着色,其颜色与 observation3
栏的颜色相同。(有关如何指定默认颜色的信息,请参阅 this post。)两者都继承 aes( x = Sample)
但使用不同的 y
和其他美学。我们通过从 data1$Sample
(可选)中删除所有小写字母和下划线来清理 X 轴标签。
library(ggplot2)
library(reshape2)
data1.long <- melt(data1, measure = 2:4) # cols 2:4 are observation1, ..., observation3
mx <- max(data1.long$value) # maximum observation value
ggplot(data1.long, aes(x = Sample, y = value)) +
geom_bar(aes(fill = variable), stat = "identity", width = 0.5, position = "dodge") +
geom_text(aes(y = mx, label = paste0(round(percentage), "%")), data = data1,
col = "#619CFF", vjust = -0.5) +
scale_x_discrete(labels = gsub("[a-z_]", "", data1$Sample))
(点击图表可放大)
注意:我们使用了这些数据。请注意,出现的一次 Sample 已更改为带有小写 s 的 Sample:
Lines <- "Sample observation1 observation2 observation3 percentage
sample1_A 163453473 131232689 61984186 30.6236955883
sample1_B 170151351 137202212 59242536 26.8866816109
sample2_A 194102849 162112484 89158170 40.4183031852
sample2_B 170642240 141888123 79925652 41.7493687378
sample3_A 192858504 161227348 90532447 41.8068248626
sample3_B 177174787 147412720 81523935 40.5463120438
sample4_A 199232380 174656081 118115358 55.6409038531
sample4_B 211128931 186848929 123552556 54.7201927527
sample5_A 186039420 152618196 87012356 40.9656544833
sample5_B 145855252 118225865 66265976 39.5744515254
sample6_A 211165202 186625116 112710053 48.5457722338
sample6_B 220522502 193191927 114882014 47.238670909"
data1 <- read.table(text = Lines, header = TRUE)
更新:小改进
关于r - ggplot 和 geom_text(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33962159/