2015-10-12 11 views
5

tôi cố gắng thêm văn bản như trong Position geom_text on dodged barplot Nhưng nó không làm việc với dữ liệu đơn giản của tôigeom_text với barplot lẩn tránh

data=data.frame(s=c(10,13,17,8), 
       pr=c("a","b","a","b"), 
       m=c(rep(as.Date('01.01.2015','%d.%m.%Y'),2), rep(as.Date('01.02.2015','%d.%m.%Y'),2))) 

Và ggplot

ggplot(data = data 
     ,aes(x = m, y = s,fill=pr ,ymax = max(s)*1.1))+ 
    geom_bar(position = "dodge",stat="identity")+ 
    geom_text(aes(y=s/2,label=paste(round(s,3),"%")),position = position_dodge(width=1))+ 
    scale_x_date(labels = date_format("%m/%y"),breaks = date_breaks("months")) 

tôi nhận được

enter image description here

Cách thêm văn bản vào đúng vị trí (ở giữa mỗi thanh)? Cảm ơn!

+0

Hãy thử 'width = 30' thay vì 'width = 1' và nó sẽ làm việc – LyzandeR

+1

trùng lặp có thể xảy ra của http://stackoverflow.com/questions/12018499/how-to- put-label-over-geom-bar-cho-mỗi-thanh-trong-r-với-ggplot2 ('ggplot (dữ liệu = dữ liệu, aes (x = as.factor (m), y = s, điền = pr, ymax = max (s) * 1.1)) + geom_bar (position = "dodge", stat = "identity") + geom_text (a (y = s/2, nhãn = dán (tròn (s, 3), "%")), position = position_dodge (.9)) + scale_x_discrete (định dạng nhãn = hàm (x) (as.Date (x), "% m /% y")) '). – lukeA

+0

LyzandeR là đúng, ở đây độ rộng của các cột không bằng 1, chúng tương ứng với số ngày trong tháng. Đối với tôi, tốt hơn là thiết lập chiều rộng là 30 (vì chúng ta có tháng với 31 và 28 ngày) đang chuyển đổi ngày thành yếu tố như lukeA advited – inscaven

Trả lời

5

Bạn có thể thử

ggplot(data = data, aes(x = as.factor(m), y = s,fill=pr ,ymax = max(s)*1.1)) + 
    geom_bar(position = "dodge", stat="identity") + 
    geom_text(aes(y=s/2,label=paste(round(s,3),"%")),position = position_dodge(.9)) + 
    scale_x_discrete(labels = function(x) format(as.Date(x), "%m/%y")) + 
    xlab("m") 
Các vấn đề liên quan