我没有使用,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)) +
Run Code Online (Sandbox Code Playgroud)
但这些数字未能显示出来.
这是我的代码:
# 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=",")
Run Code Online (Sandbox Code Playgroud)
在ggplot2中,您可以通过使用来实现此目的geom_text()
.aes()
对于这种几何形状,需要提供要显示的内容(label
)和定位.
您可以format
在调用中使用aes()
逗号作为十进制分隔符.
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()
Run Code Online (Sandbox Code Playgroud)
这样做有点像惯用语:
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()
Run Code Online (Sandbox Code Playgroud)
因为scales
包装内置了许多方便的贴标机.
希望这可以帮助.
归档时间: |
|
查看次数: |
166 次 |
最近记录: |