繁体   English   中英

在条形图上绘制值

[英]Plot values over bar graph

我没有使用r但我最近决定用它来绘制图形——因为它有很强的这样做的能力。 我想让我的图表更好。 具体来说,我会在条形图上绘制数字。 我看到了将标签添加到 ggplot 条形图并尝试使用

geom_text(aes(x=years, y=freq, ymax=freq, label=value, 
                hjust=ifelse(sign(value)>0, 1, 0)), 
            position = position_dodge(width=1)) +

但是数字没有出现。

这是我的代码:

# Load ggplot2 graphics package
library(ggplot2)

# Create dataset
dat <- data.frame(years = c("1991", "1993", "1997", "2001", "2005", "2007", "2011", "2015"),
freq = c(43.20, 52.13, 47.93, 46.29, 40.57, 53.88, 48.92, 50.92))

# Plot dataset with ggplot2
ggplot(dat, aes(years, freq)) + geom_bar(stat = "identity", width=0.55)
+ labs(x="Year",y="") + theme_classic()

# Comma as decimal mark
format(df, decimal.mark=",")

在 ggplot2 中,您可以使用geom_text()来实现这一点。 aes()需要为这个几何体提供要显示的内容( label )和定位。

您可以在aes()调用中使用format来获取逗号作为小数点分隔符。

 ggplot(dat, aes(years, freq)) + 
    geom_bar(stat = "identity", width=0.55) +
    geom_text(aes(label=format(freq,decimal.mark = ","), y=freq+1.1)) + 
    scale_y_continuous(breaks = seq(0,50,10)) + 
    theme_classic()

这样做稍微更惯用:

 library(scales)

 ggplot(dat, aes(years, freq)) + 
    geom_bar(stat = "identity", width=0.55) +
    geom_text(aes(label=comma(freq), y=freq+1.1)) + 
    scale_y_continuous(breaks = seq(0,50,10)) + 
    theme_classic()

因为scales包内置了许多方便的贴标机。

暂无
暂无

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

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