1

かなり単純な棒グラフ (つまり、geom_bar) にラベルを追加しようとしています。 position_dodge()withingeom_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
4

1 に答える 1

0

それらが適切に分散されていない主な理由は、SOA が因子変数ではないためだと思います。因子として維持する必要があります。さらに、scale_x_continuous をスキップすると、コードが機能するはずです。これは、マイナーな変更を加えてそれを行った方法です。垂直距離 (vjust) と色を好きなように調整できます。

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)
于 2015-11-14T08:39:07.490 に答える