2015-06-04 15 views
6

Tôi đã thấy câu trả lời this nhưng không thể sao chép nó.Vấn đề với geom_text khi sử dụng position_dodge

tôi nhận được dữ liệu của tôi như thế này:

df = data.frame(x = rep(sample(letters, 4), 2), 
       y = round(runif(8,1,100),0), 
       z = c(rep("group1",4), rep("group2",4))) 

# I then add a 'percent' column like so: 

df$perc[1:4] = df$y[1:4]/sum(df$y[1:4]) 
df$perc[5:8] = df$y[5:8]/sum(df$y[5:8]) 

# Which I then convert like so: 
df$perc = paste(round(df$perc * 100, 1), "%", sep="") 

# The ggplot: 
library(ggplot2) 

ggplot(df) + 
geom_bar(aes(z, y, fill=x), position="dodge", stat="identity") + 
geom_text(aes(z,y,label=perc), position=position_dodge(width=1), size=4) 

Kết quả:

enter image description here

tôi không thể tìm ra những gì tôi đã làm sai.

Trả lời

7

Chỉ một thay đổi nhỏ giải quyết được vấn đề. Bạn cần chỉ định group=x trong cuộc gọi geom_text(aes(...)) của mình.

ggplot(df) + 
geom_bar(aes(z, y, fill=x), position=position_dodge(width=1), stat="identity") + 
geom_text(aes(z,y,label=perc, group=x), position=position_dodge(width=1), size=4) 

enter image description here

+1

Hoặc di chuyển 'điền = x' đến 'cấp cao nhất' trong 'ggplot'. Sau đó biến dodging này cũng được thừa hưởng thành 'geom_text'. 'dodge <- position_dodge (width = 1)'; 'ggplot (df, aes (z, y, điền = x, nhãn = perc)) + geom_bar (position = dodge, stat =" identity ") + geom_text (position = dodge, size = 4)'. Bạn cũng tránh lặp lại 'aes (z, y,' cho mỗi 'geom'. – Henrik

Các vấn đề liên quan