簡體   English   中英

R ggplot2-為條形圖增加值

[英]R ggplot2 - adding value to bar plot

遵循以下R Cookbook中的示例

dat <- data.frame(
  time = factor(c("Lunch","Dinner"), levels=c("Lunch","Dinner")),
  total_bill = c(14.89, 17.23)
)

ggplot(data=dat, aes(x=time, y=total_bill, fill=time)) +
    geom_bar(colour="black", stat="identity") +
    guides(fill=FALSE)

如何添加total_bill的值(14.89、17.23),使其顯示在每個小節的頂部,並且四舍五入到小數點后1位,例如-14.9、17.2

上面的代碼圖

您可以這樣做:

ggplot(data=dat, aes(x=time, y=total_bill, fill=time)) +
  geom_bar(colour="black", stat="identity") +
  geom_text(aes(label = sprintf("%.1f", total_bill), y= total_bill),  vjust = 3)+
  guides(fill=FALSE)

您可以調整vjust向上或向下移動的標簽。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM