【问题标题】:Plot values over bar graph在条形图上绘制值
【发布时间】:2016-04-25 10:37:40
【问题描述】:

我没有使用r,但我最近决定用它来绘制图表——因为它的强大功能。 我想让我的图表更好。具体来说,我会在条形图上绘制数字。 我看到Adding labels to ggplot bar chart 并尝试使用

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=",")

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    在 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 包内置了许多方便的标签器。

    【讨论】:

    • 谢谢。我做了一个更改:y=freq+2,现在值更高了。 @hrbrmstr 请随时提供您更惯用的代码。
    • M. A. 这里有介绍吗。这是一个 gd 答案(我只是在其中添加了惯用的 vs )。您也可以使用nudge_y std 参数与添加到aes() y 参数来移动标签。
    • 当我使用你更惯用的代码时,我得到:Don't know how to automatically pick scale for object of type function. Defaulting to continuous Error in data.frame(y = c(44.3, 53.23, 49.03, 47.39, 41.67, 54.98, 50.02, : arguments imply differing number of rows: 8, 0
    • 之前赶时间,忘记了参数。固定。
    猜你喜欢
    • 2019-04-24
    • 2020-02-28
    • 2015-09-07
    • 2021-06-16
    • 2018-02-08
    • 2014-08-05
    • 2016-10-09
    • 2013-10-06
    相关资源
    最近更新 更多