繁体   English   中英

如何在ggplot2条形图中的标签上添加水平减淡?

[英]How to add horizontal dodge to labels in a ggplot2 bar chart?

我正在尝试将标签添加到一个相当简单的条形图(即geom_bar)中。 geom_text() position_dodge()中的geom_text()校正标签的垂直间距,但不校正水平间距。 如何使ggplot2将标签正确分散在条形上方?

library(tidyr)
library(grid)
library(ggplot2)

data = read.table('temp.dat', header=T)

data <- gather(data, SOA, RT, X0:X1000)

data$ResponseCondition = as.factor(data$ResponseCondition)
levels(data$SOA) = c(0,250,500,1000)
data$SOA = as.numeric(as.character(data$SOA))

p = ggplot(data, aes(y=RT, x=SOA, fill=ResponseCondition, ymax=RT*1.05))
p = p + geom_bar(stat='identity', position=position_dodge())
p = p + geom_text(aes(label=RT), position=position_dodge())

p = p + scale_x_continuous(breaks=c(0,250,500,1000))

p = p + ylab('Response Time (ms)')
p = p + xlab('Precue Interval (ms)')
p = p + theme_bw()
p = p + scale_fill_grey(start = 0.1, end = .9, name='Response condition')

p = p + theme(
    axis.title.x = element_text(vjust=-0.30, size=10),
    axis.title.y = element_text(vjust=1.50, size=10),
    text = element_text(size=10),
    legend.justification=c(1,1), legend.position=c(1,1),
    plot.margin = unit(rep(.5, 4), 'cm'))

ggsave('temp.png', width=10, height=7.5)

这是条形图:

条形图

这是使此示例完全正常运行所需的temp.dat内容:

ResponseCondition 0    250  500  1000
               28 1254 1056  901  864
               46 1306 1063  889  772
               64 1171  939  786  682
               82 1205  948  821  731

我认为,它们没有适当分散的主要原因是SOA不是因素变量,您应该将其保留为因素。 此外,如果跳过scale_x_continuous,则您的代码应该可以工作。 这是我通过较小的更改来完成的。 您可以按照自己喜欢的方式调整垂直距离(调整)和颜色:

library(tidyr)
library(grid)
library(ggplot2)

data = read.table('temp.dat', header=T)
data <- gather(data, SOA, RT, X0:X1000)
data$ResponseCondition = as.factor(data$ResponseCondition)
levels(data$SOA) = c(0,250,500,1000)
# data$SOA = as.numeric(as.character(data$SOA))

p = ggplot(data, aes(y=RT, x=SOA, fill=ResponseCondition, ymax=RT*1.05))
p = p + geom_bar(stat='identity', position=position_dodge())
p = p + geom_text(aes(label=RT), colour="purple", vjust=1.5, position=position_dodge(0.9), size=4)

# p = p + scale_x_continuous(breaks=c(0,250,500,1000))

p = p + ylab('Response Time (ms)')
p = p + xlab('Precue Interval (ms)')
p = p + theme_bw()
p = p + scale_fill_grey(start = 0.1, end = .9, name='Response condition')

p = p + theme(
    axis.title.x = element_text(vjust=-0.30, size=10),
    axis.title.y = element_text(vjust=1.50, size=10),
    text = element_text(size=10),
    legend.justification=c(1,1), legend.position=c(1,1),
    plot.margin = unit(rep(.5, 4), 'cm'))

ggsave('temp.png', width=10, height=7.5)

暂无
暂无

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

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